lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 1cf303ca6f91e7b6a6a7f0e734c819d7a10c2531 | 0 | FamilySearch/gedcomx-java | /**
* Copyright Intellectual Reserve, 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.familysearch.platform.ordinances;
import com.webcohesion.enunciate.metadata.qname.XmlQNameEnum;
import com.webcohesion.enunciate.metadata.qname.XmlUnknownQNameEnumValue;
import org.familysearch.platform.FamilySearchPlatform;
import org.gedcomx.common.URI;
import org.gedcomx.rt.ControlledVocabulary;
import org.gedcomx.rt.EnumURIMap;
@XmlQNameEnum(
base = XmlQNameEnum.BaseType.URI
)
public enum OrdinanceStatus implements ControlledVocabulary {
/** The ordinance is not needed because the person was born in the covenant. */
BornInCovenant,
/** The ordinance has been completed. */
Completed,
/** The ordinance can not be reserved because more information is needed about the person. */
NeedMoreInformation,
/** The ordinance can not be reserved without special permission. */
NeedPermission,
/** The ordinance is not available to be reserved. */
NotAvailable,
/** The ordinance can not be reserved because it is not needed according to the policies of the Church. */
NotNeeded,
/** The ordinance can not currently be reserved, but it is expected that the ordinance will eventually become <code>Ready</code> after a period of time. */
NotReady,
/** The ordinance can be reserved. */
Ready,
/** The ordinance has been reserved by a different user. */
ReservedByOther,
/** The ordinance has been reserved and printed by a different user. It is currently in progress of completion. */
ReservedByOtherPrinted,
/** The ordinance was reserved by a different user and shared with or assigned to Church inventory. It may be reserved by the current user. */
ReservedByOtherSharedReady,
/** The ordinance has been reserved by a different user and is waiting for prerequisite ordinances to be completed. */
ReservedByOtherWaiting,
/** The ordinance has been reserved by the current user and can be printed. */
ReservedBySelf,
/** The ordinance has been reserved and printed by the current user. It is currently in progress of completion. */
ReservedBySelfPrinted,
/** The ordinance has been reserved by the current user and shared with or assigned to Church inventory. */
ReservedBySelfShared,
/** The ordinance was reserved, shared with or assigned to Church inventory, and has been reserved and printed by a different user. */
ReservedBySelfSharedThenPrintedByOther,
/** The ordinance was reserved, shared with or assigned to Church inventory, and has been reserved by a different user. */
ReservedBySelfSharedThenReservedByOther,
/** The ordinance has been reserved by the current user and is waiting for prerequisite ordinances to be completed. */
ReservedBySelfWaiting,
// todo the following 3 Ordinance status have been renamed. These names are deprecated and will be removed.
InProgressByOther,
InProgressBySelf,
NotNeededBornInCovenant,
@XmlUnknownQNameEnumValue
OTHER;
private static final EnumURIMap<OrdinanceStatus> URI_MAP = new EnumURIMap<OrdinanceStatus>(OrdinanceStatus.class, FamilySearchPlatform.NAMESPACE);
/**
* Return the QName value for this enum.
*
* @return The QName value for this enum.
*/
public URI toQNameURI() {
return URI_MAP.toURIValue(this);
}
/**
* Get the enumeration from the QName.
*
* @param qname The qname.
* @return The enumeration.
*/
public static OrdinanceStatus fromQNameURI(URI qname) {
return URI_MAP.fromURIValue(qname);
}
}
| extensions/familysearch/familysearch-api-model/src/main/java/org/familysearch/platform/ordinances/OrdinanceStatus.java | /**
* Copyright Intellectual Reserve, 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.familysearch.platform.ordinances;
import com.webcohesion.enunciate.metadata.qname.XmlQNameEnum;
import com.webcohesion.enunciate.metadata.qname.XmlUnknownQNameEnumValue;
import org.familysearch.platform.FamilySearchPlatform;
import org.gedcomx.common.URI;
import org.gedcomx.rt.ControlledVocabulary;
import org.gedcomx.rt.EnumURIMap;
@XmlQNameEnum(
base = XmlQNameEnum.BaseType.URI
)
public enum OrdinanceStatus implements ControlledVocabulary {
/** The ordinance is not needed because the person was born in the covenant. */
BornInCovenant,
/** The ordinance has been completed. */
Completed,
/** The ordinance can not be reserved by the current user because more information is needed about the person. */
NeedMoreInformation,
/** The ordinance can not be reserved by the current user without special permission. */
NeedPermission,
/** The ordinance is not available to be reserved by the current user. */
NotAvailable,
/** The ordinance can not be reserved because it is not needed according to the policies of the Church. */
NotNeeded,
/** The ordinance can not currently be reserved by the current user, but it is expected that the ordinance will eventually become <code>Ready</code> after a period of time. */
NotReady,
/** The ordinance has been printed and is currently in progress of completion by a different user. */
PrintedByOther,
/** The ordinance was reserved, shared with or assigned to Church inventory, and has been printed by a different user. */
PrintedByOtherAfterShared,
/** The ordinance has been printed and is currently in progress of completion by the current user. */
PrintedBySelf,
/** The ordinance can be reserved by the current user. */
Ready,
/** The ordinance has been reserved by a different user. */
ReservedByOther,
/** The ordinance was reserved by a different user and shared with or assigned to Church inventory. It may be reserved by the current user. */
ReservedByOtherAndSharedReady,
/** The ordinance has been reserved by the current user and can be printed. */
ReservedBySelf,
/** The ordinance has been reserved by the current user and shared with or assigned to Church inventory. */
ReservedBySelfAndShared,
/** The ordinance has been reserved by the current user and is waiting for prerequisite ordinances to be completed. */
ReservedBySelfAndWaiting,
// todo the following 3 Ordinance status have been renamed. These names are deprecated and will be removed.
InProgressByOther,
InProgressBySelf,
NotNeededBornInCovenant,
@XmlUnknownQNameEnumValue
OTHER;
private static final EnumURIMap<OrdinanceStatus> URI_MAP = new EnumURIMap<OrdinanceStatus>(OrdinanceStatus.class, FamilySearchPlatform.NAMESPACE);
/**
* Return the QName value for this enum.
*
* @return The QName value for this enum.
*/
public URI toQNameURI() {
return URI_MAP.toURIValue(this);
}
/**
* Get the enumeration from the QName.
*
* @param qname The qname.
* @return The enumeration.
*/
public static OrdinanceStatus fromQNameURI(URI qname) {
return URI_MAP.fromURIValue(qname);
}
}
| updates for the OrdinanceStatus's
| extensions/familysearch/familysearch-api-model/src/main/java/org/familysearch/platform/ordinances/OrdinanceStatus.java | updates for the OrdinanceStatus's | <ide><path>xtensions/familysearch/familysearch-api-model/src/main/java/org/familysearch/platform/ordinances/OrdinanceStatus.java
<ide> /** The ordinance has been completed. */
<ide> Completed,
<ide>
<del> /** The ordinance can not be reserved by the current user because more information is needed about the person. */
<add> /** The ordinance can not be reserved because more information is needed about the person. */
<ide> NeedMoreInformation,
<ide>
<del> /** The ordinance can not be reserved by the current user without special permission. */
<add> /** The ordinance can not be reserved without special permission. */
<ide> NeedPermission,
<ide>
<del> /** The ordinance is not available to be reserved by the current user. */
<add> /** The ordinance is not available to be reserved. */
<ide> NotAvailable,
<ide>
<ide> /** The ordinance can not be reserved because it is not needed according to the policies of the Church. */
<ide> NotNeeded,
<ide>
<del> /** The ordinance can not currently be reserved by the current user, but it is expected that the ordinance will eventually become <code>Ready</code> after a period of time. */
<add> /** The ordinance can not currently be reserved, but it is expected that the ordinance will eventually become <code>Ready</code> after a period of time. */
<ide> NotReady,
<ide>
<del> /** The ordinance has been printed and is currently in progress of completion by a different user. */
<del> PrintedByOther,
<del>
<del> /** The ordinance was reserved, shared with or assigned to Church inventory, and has been printed by a different user. */
<del> PrintedByOtherAfterShared,
<del>
<del> /** The ordinance has been printed and is currently in progress of completion by the current user. */
<del> PrintedBySelf,
<del>
<del> /** The ordinance can be reserved by the current user. */
<add> /** The ordinance can be reserved. */
<ide> Ready,
<ide>
<ide> /** The ordinance has been reserved by a different user. */
<ide> ReservedByOther,
<ide>
<add> /** The ordinance has been reserved and printed by a different user. It is currently in progress of completion. */
<add> ReservedByOtherPrinted,
<add>
<ide> /** The ordinance was reserved by a different user and shared with or assigned to Church inventory. It may be reserved by the current user. */
<del> ReservedByOtherAndSharedReady,
<add> ReservedByOtherSharedReady,
<add>
<add> /** The ordinance has been reserved by a different user and is waiting for prerequisite ordinances to be completed. */
<add> ReservedByOtherWaiting,
<ide>
<ide> /** The ordinance has been reserved by the current user and can be printed. */
<ide> ReservedBySelf,
<ide>
<add> /** The ordinance has been reserved and printed by the current user. It is currently in progress of completion. */
<add> ReservedBySelfPrinted,
<add>
<ide> /** The ordinance has been reserved by the current user and shared with or assigned to Church inventory. */
<del> ReservedBySelfAndShared,
<add> ReservedBySelfShared,
<add>
<add> /** The ordinance was reserved, shared with or assigned to Church inventory, and has been reserved and printed by a different user. */
<add> ReservedBySelfSharedThenPrintedByOther,
<add>
<add> /** The ordinance was reserved, shared with or assigned to Church inventory, and has been reserved by a different user. */
<add> ReservedBySelfSharedThenReservedByOther,
<ide>
<ide> /** The ordinance has been reserved by the current user and is waiting for prerequisite ordinances to be completed. */
<del> ReservedBySelfAndWaiting,
<add> ReservedBySelfWaiting,
<add>
<ide>
<ide> // todo the following 3 Ordinance status have been renamed. These names are deprecated and will be removed.
<ide> InProgressByOther, |
|
Java | epl-1.0 | ae87349b8ca4ae7ebfce933d775bd5fdfd5dae46 | 0 | my76128/controller,aryantaheri/monitoring-controller,aryantaheri/monitoring-controller,opendaylight/controller,Johnson-Chou/test,mandeepdhami/controller,aryantaheri/controller,522986491/controller,tx1103mark/controller,522986491/controller,my76128/controller,Johnson-Chou/test,violinlakshmi/opendaylight,violinlakshmi/opendaylight,inocybe/odl-controller,mandeepdhami/controller,my76128/controller,tx1103mark/controller,tx1103mark/controller,my76128/controller,aryantaheri/controller,Sushma7785/OpenDayLight-Load-Balancer,Sushma7785/OpenDayLight-Load-Balancer,aryantaheri/controller,aryantaheri/monitoring-controller,aryantaheri/monitoring-controller,tx1103mark/controller,mandeepdhami/controller,violinlakshmi/opendaylight,mandeepdhami/controller,inocybe/odl-controller | package org.opendaylight.md.controller.topology.lldp.utils;
import java.nio.charset.Charset;
import org.opendaylight.controller.sal.packet.Ethernet;
import org.opendaylight.controller.sal.packet.LLDP;
import org.opendaylight.controller.sal.packet.LLDPTLV;
import org.opendaylight.controller.sal.utils.NetUtils;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LLDPDiscoveryUtils {
static Logger LOG = LoggerFactory.getLogger(LLDPDiscoveryUtils.class);
public static final Long LLDP_INTERVAL = (long) (1000*5); // Send LLDP every five seconds
public static final Long LLDP_EXPIRATION_TIME = LLDP_INTERVAL*3; // Let up to three intervals pass before we decide we are expired.
public static String macToString(byte[] mac) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
b.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
}
return b.toString();
}
public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload) {
Ethernet ethPkt = new Ethernet();
try {
ethPkt.deserialize(payload, 0,payload.length * NetUtils.NumBitsInAByte);
} catch (Exception e) {
LOG.warn("Failed to decode LLDP packet {}", e);
}
if (ethPkt.getPayload() instanceof LLDP) {
LLDP lldp = (LLDP) ethPkt.getPayload();
try {
NodeId srcNodeId = null;
NodeConnectorId srcNodeConnectorId = null;
for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) {
if (lldptlv.getType() == LLDPTLV.TLVType.Custom.getValue()) {
srcNodeConnectorId = new NodeConnectorId(LLDPTLV.getCustomString(lldptlv.getValue(), lldptlv.getLength()));
}
if (lldptlv.getType() == LLDPTLV.TLVType.SystemName.getValue()) {
String srcNodeIdString = new String(lldptlv.getValue(),Charset.defaultCharset());
srcNodeId = new NodeId(srcNodeIdString);
}
}
if(srcNodeId != null && srcNodeConnectorId != null) {
InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
.child(Node.class,new NodeKey(srcNodeId))
.child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
.toInstance();
return new NodeConnectorRef(srcInstanceId);
}
} catch (Exception e) {
LOG.warn("Caught exception ", e);
}
}
return null;
}
}
| opendaylight/md-sal/topology-lldp-discovery/src/main/java/org/opendaylight/md/controller/topology/lldp/utils/LLDPDiscoveryUtils.java | package org.opendaylight.md.controller.topology.lldp.utils;
import java.nio.charset.Charset;
import java.util.List;
import org.opendaylight.controller.sal.packet.Ethernet;
import org.opendaylight.controller.sal.packet.LLDP;
import org.opendaylight.controller.sal.packet.LLDPTLV;
import org.opendaylight.controller.sal.utils.NetUtils;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LLDPDiscoveryUtils {
static Logger LOG = LoggerFactory.getLogger(LLDPDiscoveryUtils.class);
public static final Long LLDP_INTERVAL = (long) (1000*5); // Send LLDP every five seconds
public static final Long LLDP_EXPIRATION_TIME = LLDP_INTERVAL*3; // Let up to three intervals pass before we decide we are expired.
public static String macToString(byte[] mac) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
b.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
}
return b.toString();
}
public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload) {
Ethernet ethPkt = new Ethernet();
try {
ethPkt.deserialize(payload, 0,payload.length * NetUtils.NumBitsInAByte);
} catch (Exception e) {
LOG.warn("Failed to decode LLDP packet {}", e);
}
if (ethPkt.getPayload() instanceof LLDP) {
LLDP lldp = (LLDP) ethPkt.getPayload();
try {
List<LLDPTLV> optionalTLVList = lldp.getOptionalTLVList();
if (optionalTLVList == null) {
return null;
}
NodeId srcNodeId = null;
NodeConnectorId srcNodeConnectorId = null;
for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) {
if (lldptlv.getType() == LLDPTLV.TLVType.Custom.getValue()) {
srcNodeConnectorId = new NodeConnectorId(LLDPTLV.getCustomString(lldptlv.getValue(), lldptlv.getLength()));
}
if (lldptlv.getType() == LLDPTLV.TLVType.SystemName.getValue()) {
String srcNodeIdString = new String(lldptlv.getValue(),Charset.defaultCharset());
srcNodeId = new NodeId(srcNodeIdString);
}
}
if(srcNodeId != null && srcNodeConnectorId != null) {
InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
.child(Node.class,new NodeKey(srcNodeId))
.child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
.toInstance();
return new NodeConnectorRef(srcInstanceId);
}
} catch (Exception e) {
LOG.warn("Caught exception ", e);
}
}
return null;
}
}
| Removed dead code in LLDPDiscoveryUtil
Per aboch, lldp.getOptionalTLVList() never returns null
and thus the code checking for it is dead code.
Change-Id: I23a0951313095a09cc7fbeaeb7e254c157a77f8c
Signed-off-by: Ed Warnicke <[email protected]>
| opendaylight/md-sal/topology-lldp-discovery/src/main/java/org/opendaylight/md/controller/topology/lldp/utils/LLDPDiscoveryUtils.java | Removed dead code in LLDPDiscoveryUtil | <ide><path>pendaylight/md-sal/topology-lldp-discovery/src/main/java/org/opendaylight/md/controller/topology/lldp/utils/LLDPDiscoveryUtils.java
<ide> package org.opendaylight.md.controller.topology.lldp.utils;
<ide>
<ide> import java.nio.charset.Charset;
<del>import java.util.List;
<ide>
<ide> import org.opendaylight.controller.sal.packet.Ethernet;
<ide> import org.opendaylight.controller.sal.packet.LLDP;
<ide> LLDP lldp = (LLDP) ethPkt.getPayload();
<ide>
<ide> try {
<del> List<LLDPTLV> optionalTLVList = lldp.getOptionalTLVList();
<del> if (optionalTLVList == null) {
<del> return null;
<del> }
<ide> NodeId srcNodeId = null;
<ide> NodeConnectorId srcNodeConnectorId = null;
<ide> for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) { |
|
Java | apache-2.0 | 3608c7a0d90f97a1e3777ced70f3e82a1ec2e07a | 0 | ljacomet/statistics,Terracotta-OSS/statistics | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.terracotta.context.query;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
*
* @author cdennis
*/
public class MatchersTest {
@Test
public void testSubclassOfSameClass() {
assertTrue(Matchers.subclassOf(Integer.class).matches(Integer.class));
}
@Test
public void testSubclassOfSuperClass() {
assertTrue(Matchers.subclassOf(Number.class).matches(Integer.class));
}
@Test
public void testSubclassOfInterface() {
assertTrue(Matchers.subclassOf(Comparable.class).matches(Integer.class));
}
@Test
public void testSubclassOfUnrelatedInterface() {
assertFalse(Matchers.subclassOf(CharSequence.class).matches(Integer.class));
}
@Test
public void testSubclassOfUnrelatedClass() {
assertFalse(Matchers.subclassOf(Runtime.class).matches(Integer.class));
}
@Test
public void testHasAttributeOnEmptyMap() {
assertFalse(Matchers.hasAttribute("foo", "bar").matches(Collections.emptyMap()));
}
public void testHasAttributeOnSingletonMatchingMap() {
assertTrue(Matchers.hasAttribute("foo", "bar").matches(Collections.singletonMap("foo", "bar")));
}
public void testHasAttributeOnSingletonNonMatchingMap() {
assertFalse(Matchers.hasAttribute("foo", "bar").matches(Collections.singletonMap("foo", "baz")));
}
public void testHasAttributeOnMatchingMap() {
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
map.put("alice", "bob");
assertTrue(Matchers.hasAttribute("foo", "bar").matches(map));
}
public void testHasAttributeOnNonMatchingMap() {
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "baz");
map.put("alice", "bob");
assertTrue(Matchers.hasAttribute("foo", "bar").matches(map));
}
}
| src/test/java/org/terracotta/context/query/MatchersTest.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.terracotta.context.query;
/**
*
* @author cdennis
*/
public class MatchersTest {
}
| Add partial matchers coverage
git-svn-id: 753d409225f6ed8f0d0e9345cd3d80ba4dc6ea0a@37554 591de9ec-d6d5-471c-8416-afe4a41b277d
| src/test/java/org/terracotta/context/query/MatchersTest.java | Add partial matchers coverage | <ide><path>rc/test/java/org/terracotta/context/query/MatchersTest.java
<ide> * and open the template in the editor.
<ide> */
<ide> package org.terracotta.context.query;
<add>
<add>import java.util.Collections;
<add>import java.util.HashMap;
<add>import java.util.Map;
<add>import org.junit.Test;
<add>
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertTrue;
<ide>
<ide> /**
<ide> *
<ide> */
<ide> public class MatchersTest {
<ide>
<add> @Test
<add> public void testSubclassOfSameClass() {
<add> assertTrue(Matchers.subclassOf(Integer.class).matches(Integer.class));
<add> }
<add>
<add> @Test
<add> public void testSubclassOfSuperClass() {
<add> assertTrue(Matchers.subclassOf(Number.class).matches(Integer.class));
<add> }
<add>
<add> @Test
<add> public void testSubclassOfInterface() {
<add> assertTrue(Matchers.subclassOf(Comparable.class).matches(Integer.class));
<add> }
<add>
<add> @Test
<add> public void testSubclassOfUnrelatedInterface() {
<add> assertFalse(Matchers.subclassOf(CharSequence.class).matches(Integer.class));
<add> }
<add>
<add> @Test
<add> public void testSubclassOfUnrelatedClass() {
<add> assertFalse(Matchers.subclassOf(Runtime.class).matches(Integer.class));
<add> }
<add>
<add> @Test
<add> public void testHasAttributeOnEmptyMap() {
<add> assertFalse(Matchers.hasAttribute("foo", "bar").matches(Collections.emptyMap()));
<add> }
<add>
<add> public void testHasAttributeOnSingletonMatchingMap() {
<add> assertTrue(Matchers.hasAttribute("foo", "bar").matches(Collections.singletonMap("foo", "bar")));
<add> }
<add>
<add> public void testHasAttributeOnSingletonNonMatchingMap() {
<add> assertFalse(Matchers.hasAttribute("foo", "bar").matches(Collections.singletonMap("foo", "baz")));
<add> }
<add>
<add> public void testHasAttributeOnMatchingMap() {
<add> Map<String, String> map = new HashMap<String, String>();
<add> map.put("foo", "bar");
<add> map.put("alice", "bob");
<add> assertTrue(Matchers.hasAttribute("foo", "bar").matches(map));
<add> }
<add>
<add> public void testHasAttributeOnNonMatchingMap() {
<add> Map<String, String> map = new HashMap<String, String>();
<add> map.put("foo", "baz");
<add> map.put("alice", "bob");
<add> assertTrue(Matchers.hasAttribute("foo", "bar").matches(map));
<add> }
<ide> } |
|
Java | bsd-3-clause | bc4869af8458005e71fc126fe1c9bdb42b76c8a1 | 0 | adini121/atlassian,adini121/atlassian,adini121/atlassian,adini121/atlassian | package com.atlassian.selenium.visualcomparison.utils;
import java.awt.*;
public class ScreenResolution extends Dimension implements Comparable<ScreenResolution>
{
public ScreenResolution(int width, int height)
{
super(width, height);
}
public ScreenResolution(String value)
{
String[] parts = value.split("x");
if (parts.length != 2)
{
throw new RuntimeException(value + " is not a valid screen resolution");
}
int width = Integer.parseInt(parts[0]);
int height = Integer.parseInt(parts[1]);
setSize(width, height);
}
public int compareTo(ScreenResolution other)
{
if (this.width < other.width)
{
return -1;
}
if (this.width > other.width)
{
return 1;
}
if (this.height < other.height)
{
return -1;
}
if (this.height > other.height)
{
return 1;
}
return 0;
}
public String toString()
{
return width + "x" + height;
}
public void resize(VisualComparableClient client, boolean refresh)
{
client.evaluate("window.resizeTo(" + width + ", " + height + ");");
if (refresh)
{
client.refreshAndWait();
}
}
}
| atlassian-visual-comparison/src/main/java/com/atlassian/selenium/visualcomparison/utils/ScreenResolution.java | package com.atlassian.selenium.visualcomparison.utils;
import com.atlassian.selenium.visualcomparison.VisualComparableClient;
public class ScreenResolution implements Comparable<ScreenResolution>
{
private int width;
private int height;
public ScreenResolution(int width, int height)
{
this.width = width;
this.height = height;
}
public int compareTo(ScreenResolution other)
{
if (this.width < other.width)
{
return -1;
}
if (this.width > other.width)
{
return 1;
}
if (this.height < other.height)
{
return -1;
}
if (this.height > other.height)
{
return 1;
}
return 0;
}
public ScreenResolution(String value)
{
String[] parts = value.split("x");
if (parts.length != 2)
{
throw new RuntimeException(value + " is not a valid screen resolution");
}
width = Integer.parseInt(parts[0]);
height = Integer.parseInt(parts[1]);
}
public String toString()
{
return width + "x" + height;
}
public void resize(VisualComparableClient client, boolean refresh)
{
client.evaluate("window.resizeTo(" + width + ", " + height + ");");
if (refresh)
{
client.refreshAndWait();
}
}
}
| ScreenResolution now extends Dimension.
This is the java awt version, not the selenium version. I guess there's not much point in me doing this...
| atlassian-visual-comparison/src/main/java/com/atlassian/selenium/visualcomparison/utils/ScreenResolution.java | ScreenResolution now extends Dimension. | <ide><path>tlassian-visual-comparison/src/main/java/com/atlassian/selenium/visualcomparison/utils/ScreenResolution.java
<ide> package com.atlassian.selenium.visualcomparison.utils;
<ide>
<del>import com.atlassian.selenium.visualcomparison.VisualComparableClient;
<add>import java.awt.*;
<ide>
<del>public class ScreenResolution implements Comparable<ScreenResolution>
<add>public class ScreenResolution extends Dimension implements Comparable<ScreenResolution>
<ide> {
<del> private int width;
<del> private int height;
<del>
<ide> public ScreenResolution(int width, int height)
<ide> {
<del> this.width = width;
<del> this.height = height;
<add> super(width, height);
<add> }
<add>
<add> public ScreenResolution(String value)
<add> {
<add> String[] parts = value.split("x");
<add> if (parts.length != 2)
<add> {
<add> throw new RuntimeException(value + " is not a valid screen resolution");
<add> }
<add> int width = Integer.parseInt(parts[0]);
<add> int height = Integer.parseInt(parts[1]);
<add>
<add> setSize(width, height);
<ide> }
<ide>
<ide> public int compareTo(ScreenResolution other)
<ide> return 0;
<ide> }
<ide>
<del> public ScreenResolution(String value)
<del> {
<del> String[] parts = value.split("x");
<del> if (parts.length != 2)
<del> {
<del> throw new RuntimeException(value + " is not a valid screen resolution");
<del> }
<del> width = Integer.parseInt(parts[0]);
<del> height = Integer.parseInt(parts[1]);
<del> }
<del>
<ide> public String toString()
<ide> {
<ide> return width + "x" + height; |
|
Java | apache-2.0 | 3014a6add85a476d2f9834c9655548327630831d | 0 | freiheit-com/sqlapi4j,freiheit-com/sqlapi4j,kkalass/sqlapi4j,kkalass/sqlapi4j | /**
* Copyright 2013 freiheit.com technologies gmbh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.freiheit.sqlapi4j.dao.meta;
import java.sql.Types;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* Enum of the DB Types used by tango custom sql converters.
*
* @author Klas Kalass ([email protected])
*/
@ParametersAreNonnullByDefault
public enum SqlTypes implements SqlType {
/**
* VARCHAR. Strings of varying length.
*/
VARCHAR (Types.VARCHAR, "VARCHAR"),
/**
* INTEGER. Integral values.
*/
INTEGER(Types.INTEGER, "INT"),
/**
* DOUBLE. Floating point values.
*/
DOUBLE(Types.DOUBLE, "double precision"),
/**
* TIMESTAMP. Date and time values.
*/
TIMESTAMP(Types.TIMESTAMP, "TIMESTAMP"),
/**
* BIGINT. Integral values with a larger range than {@link SqlTypes#INTEGER}.
*/
BIGINT(Types.BIGINT, "BIGINT"),
/**
* SMALLINT. Integral values with a smaller range than {@link SqlTypes#INTEGER} mostly precsion 5.
*/
SMALLINT(Types.SMALLINT, "SMALLINT"),
/**
* BOOLEAN. Boolean values.
*/
BOOLEAN(Types.BOOLEAN, "BOOLEAN"),
;
@Nonnull private final String _sqlName;
@Nonnull private final int _sqlType;
private SqlTypes(final int sqlType, final String sqlName) {
_sqlName = sqlName;
_sqlType = sqlType;
}
@Override
public String getSqlName() {
return _sqlName;
}
@Override
public int getSqlType() {
return _sqlType;
}
}
| dao/src/main/java/com/freiheit/sqlapi4j/dao/meta/SqlTypes.java | /**
* Copyright 2013 freiheit.com technologies gmbh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.freiheit.sqlapi4j.dao.meta;
import java.sql.Types;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* Enum of the DB Types used by tango custom sql converters.
*
* @author Klas Kalass ([email protected])
*/
@ParametersAreNonnullByDefault
public enum SqlTypes implements SqlType {
/**
* VARCHAR. Strings of varying length.
*/
VARCHAR (Types.VARCHAR, "VARCHAR"),
/**
* INTEGER. Integral values.
*/
INTEGER(Types.INTEGER, "INT"),
/**
* DOUBLE. Floating point values.
*/
DOUBLE(Types.DOUBLE, "double precision"),
/**
* TIMESTAMP. Date and time values.
*/
TIMESTAMP(Types.TIMESTAMP, "TIMESTAMP"),
/**
* BIGINT. Integral values with a larger range than {@link SqlTypes#INTEGER}.
*/
BIGINT(Types.BIGINT, "BIGINT"),
/**
* BOOLEAN. Boolean values.
*/
BOOLEAN(Types.BOOLEAN, "BOOLEAN"),
;
@Nonnull private final String _sqlName;
@Nonnull private final int _sqlType;
private SqlTypes(final int sqlType, final String sqlName) {
_sqlName = sqlName;
_sqlType = sqlType;
}
@Override
public String getSqlName() {
return _sqlName;
}
@Override
public int getSqlType() {
return _sqlType;
}
}
| Add SMALLINT to DbTypes
| dao/src/main/java/com/freiheit/sqlapi4j/dao/meta/SqlTypes.java | Add SMALLINT to DbTypes | <ide><path>ao/src/main/java/com/freiheit/sqlapi4j/dao/meta/SqlTypes.java
<ide> BIGINT(Types.BIGINT, "BIGINT"),
<ide>
<ide> /**
<add> * SMALLINT. Integral values with a smaller range than {@link SqlTypes#INTEGER} mostly precsion 5.
<add> */
<add> SMALLINT(Types.SMALLINT, "SMALLINT"),
<add>
<add> /**
<ide> * BOOLEAN. Boolean values.
<ide> */
<ide> BOOLEAN(Types.BOOLEAN, "BOOLEAN"), |
|
Java | apache-2.0 | 35853f06d9cf804297277181e023ade76301f7f6 | 0 | lesjaw/Olmatix | package com.olmatix.service;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.util.Log;
import com.olmatix.lesjaw.olmatix.R;
import com.olmatix.ui.activity.MainActivity;
/**
* Created by Lesjaw on 30/12/2016.
*/
public class OlmatixReceiver extends BroadcastReceiver {
String textNode;
int homestat;
int homestatcur=2;
@Override
public void onReceive(Context context, Intent intent) {
Log.d("DEBUG", "OlmatixReceiver");
String action = intent.getAction();
Log.i("DEBUG", "Broadcast received: " + action+" : " +homestat +" : "+homestatcur);
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Intent serviceIntent = new Intent(context, OlmatixService.class);
context.startService(serviceIntent);
}
if (intent.getAction().equals("com.olmatix.lesjaw.olmatix.ProximityAlert")) {
String k = LocationManager.KEY_PROXIMITY_ENTERING;
// Key for determining whether user is leaving or entering
boolean state = intent.getBooleanExtra(k, false);
//Gives whether the user is entering or leaving in boolean form
if (state) {
// Call the Notification Service or anything else that you would like to do here
//Toast.makeText(context, "You arrive at home..", Toast.LENGTH_LONG).show();
textNode = "You are entering home radius location..";
homestat = 0;
} else {
//Other custom Notification
//Toast.makeText(context, "You are leaving home..", Toast.LENGTH_LONG).show();
textNode = "You are leaving home..";
homestat=1;
}
if (homestat!=homestatcur) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
//PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = createNotification(context, notificationIntent);
notificationManager.notify(5, notification);
homestatcur = homestat;
}
}
}
private Notification createNotification(Context context, Intent intent) {
Notification notification = new Notification.Builder(context)
.setSmallIcon(R.drawable.ic_location_red) // the status icon
.setTicker(textNode) // the status text
.setWhen(System.currentTimeMillis()) // the time stamp
.setContentTitle("Olmatix location Alert!") // the label of the entry
.setContentText(textNode) // the contents of the entry
//.setContentIntent(intent) // The intent to send when the entry is clicked
.setAutoCancel(true)
.build();
return notification;
}
} | olmatix/src/main/java/com/olmatix/service/OlmatixReceiver.java | package com.olmatix.service;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.util.Log;
import com.olmatix.lesjaw.olmatix.R;
import com.olmatix.ui.activity.MainActivity;
/**
* Created by Lesjaw on 30/12/2016.
*/
public class OlmatixReceiver extends BroadcastReceiver {
String textNode;
int homestat;
int homestatcur=2;
@Override
public void onReceive(Context context, Intent intent) {
Log.d("DEBUG", "OlmatixReceiver");
String action = intent.getAction();
Log.i("DEBUG", "Broadcast received: " + action+" : " +homestat +" : "+homestatcur);
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Intent serviceIntent = new Intent(context, OlmatixService.class);
context.startService(serviceIntent);
}
if (intent.getAction().equals("com.olmatix.lesjaw.olmatix.ProximityAlert")) {
String k = LocationManager.KEY_PROXIMITY_ENTERING;
// Key for determining whether user is leaving or entering
boolean state = intent.getBooleanExtra(k, false);
//Gives whether the user is entering or leaving in boolean form
if (state) {
// Call the Notification Service or anything else that you would like to do here
//Toast.makeText(context, "You arrive at home..", Toast.LENGTH_LONG).show();
textNode = "You are entering home radius..";
homestat = 0;
} else {
//Other custom Notification
//Toast.makeText(context, "You are leaving home..", Toast.LENGTH_LONG).show();
textNode = "You are leaving home..";
homestat=1;
}
if (homestat!=homestatcur) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
//PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = createNotification(context, notificationIntent);
notificationManager.notify(5, notification);
homestatcur = homestat;
}
}
}
private Notification createNotification(Context context, Intent intent) {
Notification notification = new Notification.Builder(context)
.setSmallIcon(R.drawable.ic_location_red) // the status icon
.setTicker(textNode) // the status text
.setWhen(System.currentTimeMillis()) // the time stamp
.setContentTitle("Olmatix location Alert!") // the label of the entry
.setContentText(textNode) // the contents of the entry
//.setContentIntent(intent) // The intent to send when the entry is clicked
.setAutoCancel(true)
.build();
return notification;
}
} | fixing persitence connection
| olmatix/src/main/java/com/olmatix/service/OlmatixReceiver.java | fixing persitence connection | <ide><path>lmatix/src/main/java/com/olmatix/service/OlmatixReceiver.java
<ide> if (state) {
<ide> // Call the Notification Service or anything else that you would like to do here
<ide> //Toast.makeText(context, "You arrive at home..", Toast.LENGTH_LONG).show();
<del> textNode = "You are entering home radius..";
<add> textNode = "You are entering home radius location..";
<ide> homestat = 0;
<ide>
<ide> } else { |
|
JavaScript | mit | 7ad046aeec9f7d6ce672ee0ed7517c6cd967f797 | 0 | after12am/eisenscript | // module generate object code from ast
var Interpreter = function() {
this.name = 'Interpreter';
this.objects = [];
this.define = [];
this.rules = {};
this.computed = [];
this.maxdepth = 100;
this.depth = 0;
this.maxobjects = 1000;
this.objectnum = 0;
this.minsize = .2;
this.maxsize = 1.0;
this.seed = 'initial'; // integer or 'initial'
this.stack = [];
this.curr = {};
this.curr.matrix = new Matrix4();
this.curr.hex = Color('#ff0000');
this.curr.hsv = _.extend(Color({ hue: 0, saturation: 1, value: 1 }), { computed: false });
this.curr.blend = { color: null, strength: 0, computed: false };
this.curr.alpha = 1;
this.mt = new MersenneTwister();
}
// termination criteria
Interpreter.prototype.terminated = function() {
if (this.objectnum > this.maxobjects) return true;
if (this.depth >= this.maxdepth) return true;
return false;
}
// stack current transformation state
Interpreter.prototype.pushState = function() {
this.depth++;
this.stack.push({
matrix: this.curr.matrix.clone(),
hex: this.curr.hex.clone(),
hsv: this.curr.hsv.clone(),
blend: _.extend({}, this.curr.blend),
alpha: this.curr.alpha
});
return this;
}
// pull the parent transformation state
Interpreter.prototype.popState = function() {
if (this.stack.length > 0) {
this.curr = this.stack.pop();
this.depth--;
}
return this;
}
Interpreter.prototype.translate = function(x, y, z) {
this.curr.matrix.translate({
x: x,
y: y,
z: z
});
return this;
}
Interpreter.prototype.rotateX = function(angle) {
this.curr.matrix.rotateX(angle);
return this;
}
Interpreter.prototype.rotateY = function(angle) {
this.curr.matrix.rotateY(angle);
return this;
}
Interpreter.prototype.rotateZ = function(angle) {
this.curr.matrix.rotateZ(angle);
return this;
}
Interpreter.prototype.scale = function(x, y, z) {
this.curr.matrix.scale({
x: x,
y: y,
z: z
});
return this;
}
// make 3x3 rotation matrix to 4x4 matrix
// test: { m 1 0 0 0 .53 -.85 0 .85 .53 } box
Interpreter.prototype.makeRotate = function(v) {
this.curr.matrix.set(
v[0], v[1], v[2], 0,
v[3], v[4], v[5], 0,
v[6], v[7], v[8], 0,
0, 0, 0, 1
);
return this;
}
Interpreter.prototype.random16 = function() {
var hex = this.mt.next() * 0xffffff;
return Math.floor(hex).toString(16);
}
Interpreter.prototype.randomColor = function() {
return sprintf('#%06s', this.random16());
}
Interpreter.prototype.setColor = function(color) {
if (color === 'random') color = this.randomColor();
this.curr.hex = Color(color);
return this;
}
Interpreter.prototype.setHue = function(v) {
this.curr.hsv.computed = true;
this.curr.hsv.hue += v % 360;
return this;
}
Interpreter.prototype.setSaturation = function(v) {
this.curr.hsv.computed = true;
this.curr.hsv.saturation = clamp(this.curr.hsv.saturation * v, 0, 1);
return this;
}
Interpreter.prototype.setBrightness = function(v) {
this.curr.hsv.computed = true;
this.curr.hsv.value = clamp(this.curr.hsv.value * v, 0, 1);
return this;
}
Interpreter.prototype.setBlend = function(color, strength) {
this.curr.blend.computed = true;
this.curr.blend.color = color;
this.curr.blend.strength = this.curr.blend.strength + clamp(strength, 0, 1);
return this;
}
// execute eisenscript
Interpreter.prototype.generate = function(ast) {
// rewriting ast
var that = this;
ast.forEach(function(statement) {
switch (statement.type) {
case Symbol.Rule: that.rewriteRule(statement); break;
}
});
// pull the defines
ast.forEach(function(statement) {
switch (statement.type) {
case Symbol.Define: that.define.push(statement); break;
case Symbol.Set: that.define.push(statement); break;
case Symbol.Statement: if (statement.computed) that.computed.push(statement); break;
}
});
// creating intermediate code...
// promise
this.define.forEach(function(statement) {
switch (statement.type) {
case Symbol.Set:
switch (statement.key) {
case Symbol.Maxdepth: that.maxdepth = statement.value; break;
case Symbol.Maxobjects: that.maxobjects = statement.value; break;
case Symbol.Minsize: that.minsize = statement.value; break;
case Symbol.Maxsize: that.maxsize = statement.value; break;
case Symbol.Seed: that.seed = statement.value; break;
}
break;
case Symbol.Define:
// not implemented, but I don't think the definition statement is need.
break;
}
});
// initial value is randomised chosen integer
this.mt.setSeed(this.seed === 'initial' ? randInt(0, 65535) : this.seed);
// pull the statement of system environment
this.define.forEach(function(statement) {
switch (statement.type) {
case Symbol.Set:
if (statement.key === Symbol.Background) that.generateBackground(statement);
break;
}
});
// execute main
this.parseStatements(this.computed);
// return the intermediate code
return {
maxdepth: this.maxdepth,
maxobjects: this.maxobjects,
minsize: this.minsize,
maxsize: this.maxsize,
seed: this.seed,
objects: this.objects
}
}
// rewrite subtree related to rule statement
Interpreter.prototype.rewriteRule = function(rule) {
rule.params.forEach(function(param) {
if (param.type === Symbol.Modifier) {
switch (param.key) {
case Symbol.Weight: rule.weight = param.value; break;
case Symbol.Maxdepth: rule.maxdepth = param.value; rule.alternate = param.alternate; break;
}
}
});
if (!this.rules[rule.id]) this.rules[rule.id] = [];
this.rules[rule.id].push(rule);
return this;
}
// execute statements
Interpreter.prototype.parseStatements = function(statements) {
var i = 0, len = statements.length;
while (i < len) {
if (this.terminated()) break;
this.parseStatement(statements[i], 0);
i++;
}
return this;
}
// execute a statement
Interpreter.prototype.parseStatement = function(statement, index) {
// parse transformation expression
var expr = statement.exprs[index];
if (expr) {
this.pushState();
for (var i = 0; i < expr.left; i++) {
if (this.terminated()) break;
this.parseTransformStatement(expr.right);
// if statement.exprs[index + 1] is undefined, it would break the transformation loops.
this.parseStatement(statement, index + 1);
}
this.popState();
return this;
}
// if not primitive, call rule and parse next transformation loops
if (_.values(Primitive).indexOf(statement.id) === -1) {
var rule = this.sampling(statement.id);
if (rule) this.parseStatements(rule.body);
return this;
}
// achieve the end of nested transformation loops
this.generatePrimitive(statement);
return this;
}
// break down transformation set
Interpreter.prototype.parseTransformStatement = function(transform) {
var i = 0, len = transform.properties.length;
while (i < len) {
this.parseTransform(transform.properties[i]);
i++;
}
return this;
}
// parse transformation property
Interpreter.prototype.parseTransform = function(property) {
var v = property.value;
switch (property.key) {
case Symbol.XShift: this.translate(v, 0, 0); break;
case Symbol.YShift: this.translate(0, v, 0); break;
case Symbol.ZShift: this.translate(0, 0, v); break;
case Symbol.RotateX: this.rotateX(degToRad(v)); break;
case Symbol.RotateY: this.rotateY(degToRad(v)); break;
case Symbol.RotateZ: this.rotateZ(degToRad(v)); break;
case Symbol.Size: this.scale(v.x, v.y, v.z); break;
case Symbol.Matrix: this.makeRotate(v); break;
case Symbol.Color: this.setColor(v); break;
case Symbol.Hue: this.setHue(v); break;
case Symbol.Saturation: this.setSaturation(v); break;
case Symbol.Brightness: this.setBrightness(v); break;
case Symbol.Blend: this.setBlend(property.color, property.strength); break;
case Symbol.Alpha: this.curr.alpha *= v; break;
}
return this;
}
// create primitive object and stack it as intermediate code for renderer
Interpreter.prototype.generatePrimitive = function(statement) {
// if achieved maxobjects
this.objectnum++;
if (this.terminated()) return;
// blend the current color with the specified color
if (this.curr.blend.computed) {
this.curr.hex = this.curr.hex.toHSV();
var blend = Color(this.curr.blend.color).toHSV();
this.curr.hex.hue += (blend.hue - this.curr.hex.hue) * this.curr.blend.strength / 6;
this.curr.hex.hue %= 360;
}
// primitive object
this.objects.push({
type: Type.Primitive,
name: statement.id,
matrix: this.curr.matrix.clone(),
color: this.curr.hsv.computed ? this.curr.hex.blend(this.curr.hsv, 1).toCSS() : this.curr.hex.toCSS(),
opacity: this.curr.alpha,
depth: this.depth
});
}
// create background object code and stack it as intermediate code for renderer
Interpreter.prototype.generateBackground = function(statement) {
this.objects.push({
type: Type.Background,
color: statement.value
});
}
// randomly choose one of the rules according to their weights
Interpreter.prototype.sampling = function(name, retry) {
if (!this.rules[name]) {
throw new Error(
sprintf("ReferenceError: '%s' is not defined. As reported by eisenscript interpreter.", name),
sprintf("%s.js", this.name)
);
}
// sum weights of each rules
var sum = 0;
this.rules[name].forEach(function(rule) {
rule.weight = rule.weight || 1;
sum += rule.weight;
});
// choosing...
var rand = this.mt.next() * sum;
var chosen;
for (var i = 0; i < this.rules[name].length; i++) {
var rule = this.rules[name][i];
if (rule.weight - rand < 0) {
rand -= rule.weight
continue;
}
chosen = rule;
break;
}
// if rule could not be selected, interpreter tries to choose until 3 times
if (!chosen) {
retry = retry || 0;
if (retry < 3) return this.sampling(name, ++retry);
// if achieve max retry count
return false;
}
// if achieved maxdepth
chosen.depth = (chosen.depth || 0) + 1;
if (chosen.maxdepth && chosen.maxdepth < chosen.depth) {
if (chosen.alternate) return this.sampling(chosen.alternate);
return false;
}
// the rule randomly chosen
return chosen;
}
| src/interpreter.js | // module generate object code from ast
var Interpreter = function() {
this.name = 'Interpreter';
this.objects = [];
this.define = [];
this.rules = {};
this.computed = [];
this.maxdepth = 100;
this.depth = 0;
this.maxobjects = 1000;
this.objectnum = 0;
this.minsize = .2;
this.maxsize = 1.0;
this.seed = 'initial'; // integer or 'initial'
this.stack = [];
this.curr = {};
this.curr.matrix = new Matrix4();
this.curr.hex = Color('#ff0000');
this.curr.hsv = _.extend(Color({ hue: 0, saturation: 1, value: 1 }), { computed: false });
this.curr.blend = { color: null, strength: 0, computed: false };
this.curr.alpha = 1;
this.mt = new MersenneTwister();
}
// termination criteria
Interpreter.prototype.terminated = function() {
if (this.objectnum > this.maxobjects) return true;
if (this.depth >= this.maxdepth) return true;
return false;
}
// stack current transformation state
Interpreter.prototype.pushState = function() {
this.depth++;
this.stack.push({
matrix: this.curr.matrix.clone(),
hex: this.curr.hex.clone(),
hsv: this.curr.hsv.clone(),
blend: _.extend({}, this.curr.blend),
alpha: this.curr.alpha
});
return this;
}
// pull the parent transformation state
Interpreter.prototype.popState = function() {
if (this.stack.length > 0) {
this.curr = this.stack.pop();
this.depth--;
}
return this;
}
Interpreter.prototype.translate = function(x, y, z) {
this.curr.matrix.translate({
x: x,
y: y,
z: z
});
return this;
}
Interpreter.prototype.rotateX = function(angle) {
this.curr.matrix.rotateX(angle);
return this;
}
Interpreter.prototype.rotateY = function(angle) {
this.curr.matrix.rotateY(angle);
return this;
}
Interpreter.prototype.rotateZ = function(angle) {
this.curr.matrix.rotateZ(angle);
return this;
}
Interpreter.prototype.scale = function(x, y, z) {
this.curr.matrix.scale({
x: x,
y: y,
z: z
});
return this;
}
// make 3x3 rotation matrix to 4x4 matrix
// test: { m 1 0 0 0 .53 -.85 0 .85 .53 } box
Interpreter.prototype.makeRotate = function(v) {
this.curr.matrix.set(
v[0], v[1], v[2], 0,
v[3], v[4], v[5], 0,
v[6], v[7], v[8], 0,
0, 0, 0, 1
);
return this;
}
Interpreter.prototype.random16 = function() {
var hex = this.mt.next() * 0xffffff;
return sprintf('#%06s', Math.floor(hex).toString(16));
}
Interpreter.prototype.setColor = function(color) {
if (color === 'random') color = this.random16();
this.curr.hex = Color(color);
return this;
}
Interpreter.prototype.setHue = function(v) {
this.curr.hsv.computed = true;
this.curr.hsv.hue += v % 360;
return this;
}
Interpreter.prototype.setSaturation = function(v) {
this.curr.hsv.computed = true;
this.curr.hsv.saturation = clamp(this.curr.hsv.saturation * v, 0, 1);
return this;
}
Interpreter.prototype.setBrightness = function(v) {
this.curr.hsv.computed = true;
this.curr.hsv.value = clamp(this.curr.hsv.value * v, 0, 1);
return this;
}
Interpreter.prototype.setBlend = function(color, strength) {
this.curr.blend.computed = true;
this.curr.blend.color = color;
this.curr.blend.strength = this.curr.blend.strength + clamp(strength, 0, 1);
return this;
}
// execute eisenscript
Interpreter.prototype.generate = function(ast) {
// rewriting ast
var that = this;
ast.forEach(function(statement) {
switch (statement.type) {
case Symbol.Rule: that.rewriteRule(statement); break;
}
});
// pull the defines
ast.forEach(function(statement) {
switch (statement.type) {
case Symbol.Define: that.define.push(statement); break;
case Symbol.Set: that.define.push(statement); break;
case Symbol.Statement: if (statement.computed) that.computed.push(statement); break;
}
});
// creating intermediate code...
// promise
this.define.forEach(function(statement) {
switch (statement.type) {
case Symbol.Set:
switch (statement.key) {
case Symbol.Maxdepth: that.maxdepth = statement.value; break;
case Symbol.Maxobjects: that.maxobjects = statement.value; break;
case Symbol.Minsize: that.minsize = statement.value; break;
case Symbol.Maxsize: that.maxsize = statement.value; break;
case Symbol.Seed: that.seed = statement.value; break;
}
break;
case Symbol.Define:
// not implemented, but I don't think the definition statement is need.
break;
}
});
// initial value is randomised chosen integer
this.mt.setSeed(this.seed === 'initial' ? randInt(0, 65535) : this.seed);
// pull the statement of system environment
this.define.forEach(function(statement) {
switch (statement.type) {
case Symbol.Set:
if (statement.key === Symbol.Background) that.generateBackground(statement);
break;
}
});
// execute main
this.parseStatements(this.computed);
// return the intermediate code
return {
maxdepth: this.maxdepth,
maxobjects: this.maxobjects,
minsize: this.minsize,
maxsize: this.maxsize,
seed: this.seed,
objects: this.objects
}
}
// rewrite subtree related to rule statement
Interpreter.prototype.rewriteRule = function(rule) {
rule.params.forEach(function(param) {
if (param.type === Symbol.Modifier) {
switch (param.key) {
case Symbol.Weight: rule.weight = param.value; break;
case Symbol.Maxdepth: rule.maxdepth = param.value; rule.alternate = param.alternate; break;
}
}
});
if (!this.rules[rule.id]) this.rules[rule.id] = [];
this.rules[rule.id].push(rule);
return this;
}
// execute statements
Interpreter.prototype.parseStatements = function(statements) {
var i = 0, len = statements.length;
while (i < len) {
if (this.terminated()) break;
this.parseStatement(statements[i], 0);
i++;
}
return this;
}
// execute a statement
Interpreter.prototype.parseStatement = function(statement, index) {
// parse transformation expression
var expr = statement.exprs[index];
if (expr) {
this.pushState();
for (var i = 0; i < expr.left; i++) {
if (this.terminated()) break;
this.parseTransformStatement(expr.right);
// if statement.exprs[index + 1] is undefined, it would break the transformation loops.
this.parseStatement(statement, index + 1);
}
this.popState();
return this;
}
// if not primitive, call rule and parse next transformation loops
if (_.values(Primitive).indexOf(statement.id) === -1) {
var rule = this.sampling(statement.id);
if (rule) this.parseStatements(rule.body);
return this;
}
// achieve the end of nested transformation loops
this.generatePrimitive(statement);
return this;
}
// break down transformation set
Interpreter.prototype.parseTransformStatement = function(transform) {
var i = 0, len = transform.properties.length;
while (i < len) {
this.parseTransform(transform.properties[i]);
i++;
}
return this;
}
// parse transformation property
Interpreter.prototype.parseTransform = function(property) {
var v = property.value;
switch (property.key) {
case Symbol.XShift: this.translate(v, 0, 0); break;
case Symbol.YShift: this.translate(0, v, 0); break;
case Symbol.ZShift: this.translate(0, 0, v); break;
case Symbol.RotateX: this.rotateX(degToRad(v)); break;
case Symbol.RotateY: this.rotateY(degToRad(v)); break;
case Symbol.RotateZ: this.rotateZ(degToRad(v)); break;
case Symbol.Size: this.scale(v.x, v.y, v.z); break;
case Symbol.Matrix: this.makeRotate(v); break;
case Symbol.Color: this.setColor(v); break;
case Symbol.Hue: this.setHue(v); break;
case Symbol.Saturation: this.setSaturation(v); break;
case Symbol.Brightness: this.setBrightness(v); break;
case Symbol.Blend: this.setBlend(property.color, property.strength); break;
case Symbol.Alpha: this.curr.alpha *= v; break;
}
return this;
}
// create primitive object and stack it as intermediate code for renderer
Interpreter.prototype.generatePrimitive = function(statement) {
// if achieved maxobjects
this.objectnum++;
if (this.terminated()) return;
// blend the current color with the specified color
if (this.curr.blend.computed) {
this.curr.hex = this.curr.hex.toHSV();
var blend = Color(this.curr.blend.color).toHSV();
this.curr.hex.hue += (blend.hue - this.curr.hex.hue) * this.curr.blend.strength / 6;
this.curr.hex.hue %= 360;
}
// primitive object
this.objects.push({
type: Type.Primitive,
name: statement.id,
matrix: this.curr.matrix.clone(),
color: this.curr.hsv.computed ? this.curr.hex.blend(this.curr.hsv, 1).toCSS() : this.curr.hex.toCSS(),
opacity: this.curr.alpha,
depth: this.depth
});
}
// create background object code and stack it as intermediate code for renderer
Interpreter.prototype.generateBackground = function(statement) {
this.objects.push({
type: Type.Background,
color: statement.value
});
}
// randomly choose one of the rules according to their weights
Interpreter.prototype.sampling = function(name, retry) {
if (!this.rules[name]) {
throw new Error(
sprintf("ReferenceError: '%s' is not defined. As reported by eisenscript interpreter.", name),
sprintf("%s.js", this.name)
);
}
// sum weights of each rules
var sum = 0;
this.rules[name].forEach(function(rule) {
rule.weight = rule.weight || 1;
sum += rule.weight;
});
// choosing...
var rand = this.mt.next() * sum;
var chosen;
for (var i = 0; i < this.rules[name].length; i++) {
var rule = this.rules[name][i];
if (rule.weight - rand < 0) {
rand -= rule.weight
continue;
}
chosen = rule;
break;
}
// if rule could not be selected, interpreter tries to choose until 3 times
if (!chosen) {
retry = retry || 0;
if (retry < 3) return this.sampling(name, ++retry);
// if achieve max retry count
return false;
}
// if achieved maxdepth
chosen.depth = (chosen.depth || 0) + 1;
if (chosen.maxdepth && chosen.maxdepth < chosen.depth) {
if (chosen.alternate) return this.sampling(chosen.alternate);
return false;
}
// the rule randomly chosen
return chosen;
}
| refine source | src/interpreter.js | refine source | <ide><path>rc/interpreter.js
<ide>
<ide> Interpreter.prototype.random16 = function() {
<ide> var hex = this.mt.next() * 0xffffff;
<del> return sprintf('#%06s', Math.floor(hex).toString(16));
<add> return Math.floor(hex).toString(16);
<add>}
<add>
<add>Interpreter.prototype.randomColor = function() {
<add> return sprintf('#%06s', this.random16());
<ide> }
<ide>
<ide> Interpreter.prototype.setColor = function(color) {
<del> if (color === 'random') color = this.random16();
<add> if (color === 'random') color = this.randomColor();
<ide> this.curr.hex = Color(color);
<ide> return this;
<ide> } |
|
JavaScript | mit | 6ef1603fe765a25d53f7cf488fde64b360e42f0c | 0 | nidesky/timed-queue,teambition/timed-queue | 'use strict'
// **Github:** https://github.com/teambition/timed-queue
//
// **License:** MIT
var fs = require('fs')
var util = require('util')
var thunks = require('thunks')
var redis = require('thunk-redis')
var EventEmitter = require('events').EventEmitter
var luaScript = fs.readFileSync(__dirname + '/lua/queue.lua', {encoding: 'utf8'})
var thunk = thunks()
module.exports = TimedQueue
function TimedQueue (options) {
options = options || {}
this.prefix = options.prefix || 'TIMEDQ'
this.queuesKey = '{' + this.prefix + '}:QUEUES'
this.count = Math.floor(options.count) || 64
this.interval = Math.floor(options.interval) || 1000 * 120
this.expire = Math.floor(options.expire) || this.interval * 5
this.retry = Math.floor(options.retry) || Math.floor(this.interval / 2)
this.accuracy = Math.floor(options.accuracy) || Math.floor(this.interval / 5)
this.autoScan = options.autoScan !== false
this.redis = null
this.timer = null
this.scanTime = 0
this.scanning = false
this.scanQueue = null
this.delay = this.interval
this.queues = Object.create(null)
this.scanQueue = null
var ctx = this
this.thunk = thunks(function (error) {
ctx.emit('error', error)
})
EventEmitter.call(this)
}
util.inherits(TimedQueue, EventEmitter)
TimedQueue.prototype.connect = function () {
var ctx = this
if (this.redis) return this
this.redis = redis.createClient.apply(null, arguments)
.on('connect', function () {
ctx.emit('connect')
})
.on('error', function (error) {
ctx.emit('error', error)
})
.on('close', function () {
ctx.emit('close')
})
this.scanQueue = this.thunk.persist.call(this, this.redis.script('load', luaScript))
// auto scan jobs
if (this.autoScan) {
thunk.delay.call(this, Math.random() * this.interval)(function () {
this.scan()
})
}
return this
}
TimedQueue.prototype.queue = function (queueName, options) {
validateString(queueName)
if (!this.queues[queueName]) this.queues[queueName] = new Queue(this, queueName, options)
else if (options) this.queues[queueName].init(options)
return this.queues[queueName]
}
TimedQueue.prototype.destroyQueue = function (queueName) {
return thunk.call(this, function (done) {
var redis = this.redis
var queue = this.queue(queueName)
delete this.queues[queueName]
thunk.all([
redis.srem(this.queuesKey, queue.name),
redis.del(queue.queueOptionsKey),
redis.del(queue.activeQueueKey),
redis.del(queue.queueKey)
])(function (err) {
done(err, null)
})
})
}
TimedQueue.prototype.scan = function () {
if (this.scanning || !this.redis) return this
var ctx = this
var scanStart
this.scanning = true
this.scanTime = scanStart = Date.now()
this.redis.smembers(this.queuesKey)(function (err, queues) {
if (err) throw err
ctx.emit('scanStart', queues.length)
return thunk.seq(queues.map(function (queue) {
return ctx.queue(queue).scan()
}))
})(function (err, queueScores) {
if (err) ctx.emit('error', err)
else {
ctx.emit('scanEnd', queueScores.length, Date.now() - scanStart)
var count = 0
var score = queueScores.reduce(function (prev, scores) {
return prev + scores.reduce(function (p, s) {
count++
return p + s
}, 0)
}, 0)
if (count) ctx.regulateFreq(score / count)
}
if (!ctx.timer && ctx.scanning) {
ctx.scanning = false
ctx.scan()
} else ctx.scanning = false
})
clearTimeout(this.timer)
this.timer = setTimeout(function () {
ctx.timer = null
if (!ctx.scanning) ctx.scan()
}, this.delay)
return this
}
TimedQueue.prototype.stop = function () {
clearTimeout(this.timer)
this.scanning = false
this.timer = null
return this
}
TimedQueue.prototype.close = function () {
this.stop()
this.redis.clientEnd()
this.redis = null
return this
}
// x > 0 | 2 - 1 / (1 + x)
// x < 0 | 1 / (1 - x)
TimedQueue.prototype.regulateFreq = function (factor) {
if (factor < -0.05) this.delay = Math.max(this.delay / (1 - factor), this.interval / 10)
else if (factor > 0.05) this.delay = Math.min(this.delay * (2 - 1 / (1 + factor)), this.interval * 5)
return this
}
function Queue (timedQueue, queueName, options) {
this.root = timedQueue
this.name = queueName
this.queueKey = '{' + timedQueue.prefix + ':' + queueName + '}' // hash tag
this.activeQueueKey = this.queueKey + ':-'
this.queueOptionsKey = this.queueKey + ':O'
this.init(options)
EventEmitter.call(this)
}
util.inherits(Queue, EventEmitter)
Queue.prototype.init = function (options) {
var root = this.root
root.thunk(root.redis.sadd(root.queuesKey, this.name))()
if (!options) return this
root.thunk(root.redis.hmset(this.queueOptionsKey, {
count: options.count || root.count,
retry: options.retry || root.retry,
expire: options.expire || root.expire,
accuracy: options.accuracy || root.accuracy
}))()
return this
}
Queue.prototype.addjob = function (job, timing) {
var args = Array.isArray(job) ? job : slice(arguments)
return thunk.call(this, function (done) {
var data = [this.queueKey]
var current = Date.now()
for (var i = 0, l = args.length || 2; i < l; i += 2) {
validateString(args[i])
timing = Math.floor(args[i + 1])
if (!timing || timing <= current) throw new Error(String(args[i + 1]) + ' is invalid time')
data.push(timing, args[i])
}
this.root.redis.zadd(data)(done)
})
}
Queue.prototype.show = function (job) {
return thunk.call(this, function (done) {
var ctx = this
validateString(job)
ctx.root.redis.zscore(ctx.queueKey, job)(function (err, timing) {
if (err) throw err
if (timing) return new Job(ctx.name, job, timing, 0, 0)
return this.hget(ctx.activeQueueKey, job)(function (err, times) {
if (err) throw err
if (!times) return null
times = times.split(':')
return new Job(ctx.name, job, times[0], times[1], times.length - 2)
})
})(done)
})
}
Queue.prototype.deljob = function (job) {
var args = Array.isArray(job) ? job : slice(arguments)
return thunk.call(this, function (done) {
var ctx = this
for (var i = 0, l = args.length || 1; i < l; i++) validateString(args[i])
args.unshift(ctx.queueKey)
ctx.root.redis.zrem(args)(function (err, count) {
if (err) throw err
args[0] = ctx.activeQueueKey
return this.hdel(args)(function (err, _count) {
if (err) throw err
return count + _count
})
})(done)
})
}
Queue.prototype.getjobs = function (scanActive) {
return thunk.call(this, function (done) {
var ctx = this
var root = this.root
var timestamp = Date.now()
thunk(root.scanQueue)(function (_, luaSHA) {
return root.redis.evalsha(luaSHA, 3,
ctx.queueKey, ctx.activeQueueKey, ctx.queueOptionsKey,
root.count, root.retry, root.expire, root.accuracy, timestamp, +(scanActive !== false)
)
})(function (err, res) {
if (err) throw err
return new ScanResult(ctx.name, timestamp, res)
})(done)
})
}
Queue.prototype.ackjob = function (job) {
var args = Array.isArray(job) ? job : slice(arguments)
return thunk.call(this, function (done) {
for (var i = 0, l = args.length || 1; i < l; i++) validateString(args[i])
args.unshift(this.activeQueueKey)
return this.root.redis.hdel(args)(done)
})
}
Queue.prototype.scan = function () {
return thunk.call(this, function (done) {
var ctx = this
var scores = []
var listener = ctx.listenerCount ? ctx.listenerCount('job') : EventEmitter.listenerCount(ctx, 'job')
if (!listener) throw new Error('"job" listener required!')
getjobs()
function getjobs (err, res) {
if (err) return done(err)
if (res) {
res.jobs.map(function (job) {
if (!job.retryCount) scores.push((job.timing - job.active) / res.retry)
process.nextTick(function () {
ctx.emit('job', job)
})
})
if (!res.hasMore) return done(null, scores)
}
ctx.getjobs(!res)(getjobs)
}
})
}
Queue.prototype.len = function () {
return thunk.call(this, function (done) {
return this.root.redis.zcard(this.queueKey)(done)
})
}
Queue.prototype.showActive = function () {
return thunk.call(this, function (done) {
var ctx = this
return this.root.redis.hgetall(this.activeQueueKey)(function (err, res) {
if (err) throw err
return Object.keys(res)
.map(function (job) {
var times = res[job].split(':')
return new Job(ctx.name, job, times[0], times[1], times.length - 2)
}).sort(function (a, b) {
return a.timing - b.timing
})
})(done)
})
}
function Job (queue, job, timing, active, retryCount) {
this.queue = queue
this.job = job
this.timing = +timing
this.active = +active
this.retryCount = +retryCount
}
function ScanResult (name, timestamp, res) {
var jobs = res[0]
this.retry = +res[1]
this.hasMore = +res[2]
this.jobs = []
for (var i = 0, l = jobs.length - 2; i < l; i += 3) {
this.jobs.push(new Job(name, jobs[i], jobs[i + 1], timestamp, jobs[i + 2]))
}
}
function slice (args, start) {
start = start || 0
if (start >= args.length) return []
var len = args.length
var ret = Array(len - start)
while (len-- > start) ret[len - start] = args[len]
return ret
}
function validateString (str) {
if (typeof str !== 'string' || !str) throw new TypeError(String(str) + ' is invalid string')
}
| index.js | 'use strict'
// **Github:** https://github.com/teambition/timed-queue
//
// **License:** MIT
var fs = require('fs')
var util = require('util')
var thunks = require('thunks')
var redis = require('thunk-redis')
var EventEmitter = require('events').EventEmitter
var luaScript = fs.readFileSync(__dirname + '/lua/queue.lua', {encoding: 'utf8'})
var thunk = thunks()
module.exports = TimedQueue
function TimedQueue (options) {
options = options || {}
this.prefix = options.prefix || 'TIMEDQ'
this.queuesKey = '{' + this.prefix + '}:QUEUES'
this.count = Math.floor(options.count) || 64
this.interval = Math.floor(options.interval) || 1000 * 120
this.expire = Math.floor(options.expire) || this.interval * 5
this.retry = Math.floor(options.retry) || Math.floor(this.interval / 2)
this.accuracy = Math.floor(options.accuracy) || Math.floor(this.interval / 5)
this.autoScan = options.autoScan !== false
this.redis = null
this.timer = null
this.scanTime = 0
this.scanning = false
this.scanQueue = null
this.delay = this.interval
this.queues = Object.create(null)
this.scanQueue = null
var ctx = this
this.thunk = thunks(function (error) {
ctx.emit('error', error)
})
EventEmitter.call(this)
}
util.inherits(TimedQueue, EventEmitter)
TimedQueue.prototype.connect = function () {
var ctx = this
if (this.redis) return this
this.redis = redis.createClient.apply(null, arguments)
.on('connect', function () {
ctx.emit('connect')
})
.on('error', function (error) {
ctx.emit('error', error)
})
.on('close', function () {
ctx.emit('close')
})
this.scanQueue = this.thunk.persist.call(this, this.redis.script('load', luaScript))
// auto scan jobs
if (this.autoScan) {
thunk.delay.call(this, Math.random() * this.interval)(function () {
this.scan()
})
}
return this
}
TimedQueue.prototype.queue = function (queueName, options) {
validateString(queueName)
if (!this.queues[queueName]) this.queues[queueName] = new Queue(this, queueName, options)
else if (options) this.queues[queueName].init(options)
return this.queues[queueName]
}
TimedQueue.prototype.destroyQueue = function (queueName) {
return thunk.call(this, function (done) {
var redis = this.redis
var queue = this.queue(queueName)
delete this.queues[queueName]
thunk.all([
redis.srem(this.queuesKey, queue.name),
redis.del(queue.queueOptionsKey),
redis.del(queue.activeQueueKey),
redis.del(queue.queueKey)
])(function (err) {
done(err, null)
})
})
}
TimedQueue.prototype.scan = function () {
if (this.scanning || !this.redis) return this
var ctx = this
var scanStart
this.scanning = true
this.scanTime = scanStart = Date.now()
this.redis.smembers(this.queuesKey)(function (err, queues) {
if (err) throw err
ctx.emit('scanStart', queues.length)
return thunk.seq(queues.map(function (queue) {
return ctx.queue(queue).scan()
}))
})(function (err, queueScores) {
if (err) ctx.emit('error', err)
else {
ctx.emit('scanEnd', queueScores.length, Date.now() - scanStart)
var count = 0
var score = queueScores.reduce(function (prev, scores) {
return prev + scores.reduce(function (p, s) {
count++
return p + s
}, 0)
}, 0)
if (count) ctx.regulateFreq(score / count)
}
if (!ctx.timer && ctx.scanning) {
ctx.scanning = false
ctx.scan()
} else ctx.scanning = false
})
clearTimeout(this.timer)
this.timer = setTimeout(function () {
ctx.timer = null
if (!ctx.scanning) ctx.scan()
}, this.delay)
return this
}
TimedQueue.prototype.stop = function () {
clearTimeout(this.timer)
this.scanning = false
this.timer = null
return this
}
TimedQueue.prototype.close = function () {
this.stop()
this.redis.clientEnd()
this.redis = null
return this
}
TimedQueue.prototype.regulateFreq = function (factor) {
if (factor < -0.1) this.delay = Math.max(this.delay * (1 + factor), this.interval / 10)
else if (factor > 0.1) this.delay = Math.min(this.delay * (1 + factor), this.interval * 5)
return this
}
function Queue (timedQueue, queueName, options) {
this.root = timedQueue
this.name = queueName
this.queueKey = '{' + timedQueue.prefix + ':' + queueName + '}' // hash tag
this.activeQueueKey = this.queueKey + ':-'
this.queueOptionsKey = this.queueKey + ':O'
this.init(options)
EventEmitter.call(this)
}
util.inherits(Queue, EventEmitter)
Queue.prototype.init = function (options) {
var root = this.root
root.thunk(root.redis.sadd(root.queuesKey, this.name))()
if (!options) return this
root.thunk(root.redis.hmset(this.queueOptionsKey, {
count: options.count || root.count,
retry: options.retry || root.retry,
expire: options.expire || root.expire,
accuracy: options.accuracy || root.accuracy
}))()
return this
}
Queue.prototype.addjob = function (job, timing) {
var args = Array.isArray(job) ? job : slice(arguments)
return thunk.call(this, function (done) {
var data = [this.queueKey]
var current = Date.now()
for (var i = 0, l = args.length || 2; i < l; i += 2) {
validateString(args[i])
timing = Math.floor(args[i + 1])
if (!timing || timing <= current) throw new Error(String(args[i + 1]) + ' is invalid time')
data.push(timing, args[i])
}
this.root.redis.zadd(data)(done)
})
}
Queue.prototype.show = function (job) {
return thunk.call(this, function (done) {
var ctx = this
validateString(job)
ctx.root.redis.zscore(ctx.queueKey, job)(function (err, timing) {
if (err) throw err
if (timing) return new Job(ctx.name, job, timing, 0, 0)
return this.hget(ctx.activeQueueKey, job)(function (err, times) {
if (err) throw err
if (!times) return null
times = times.split(':')
return new Job(ctx.name, job, times[0], times[1], times.length - 2)
})
})(done)
})
}
Queue.prototype.deljob = function (job) {
var args = Array.isArray(job) ? job : slice(arguments)
return thunk.call(this, function (done) {
var ctx = this
for (var i = 0, l = args.length || 1; i < l; i++) validateString(args[i])
args.unshift(ctx.queueKey)
ctx.root.redis.zrem(args)(function (err, count) {
if (err) throw err
args[0] = ctx.activeQueueKey
return this.hdel(args)(function (err, _count) {
if (err) throw err
return count + _count
})
})(done)
})
}
Queue.prototype.getjobs = function (scanActive) {
return thunk.call(this, function (done) {
var ctx = this
var root = this.root
var timestamp = Date.now()
thunk(root.scanQueue)(function (_, luaSHA) {
return root.redis.evalsha(luaSHA, 3,
ctx.queueKey, ctx.activeQueueKey, ctx.queueOptionsKey,
root.count, root.retry, root.expire, root.accuracy, timestamp, +(scanActive !== false)
)
})(function (err, res) {
if (err) throw err
return new ScanResult(ctx.name, timestamp, res)
})(done)
})
}
Queue.prototype.ackjob = function (job) {
var args = Array.isArray(job) ? job : slice(arguments)
return thunk.call(this, function (done) {
for (var i = 0, l = args.length || 1; i < l; i++) validateString(args[i])
args.unshift(this.activeQueueKey)
return this.root.redis.hdel(args)(done)
})
}
Queue.prototype.scan = function () {
return thunk.call(this, function (done) {
var ctx = this
var scores = []
var listener = ctx.listenerCount ? ctx.listenerCount('job') : EventEmitter.listenerCount(ctx, 'job')
if (!listener) throw new Error('"job" listener required!')
getjobs()
function getjobs (err, res) {
if (err) return done(err)
if (res) {
res.jobs.map(function (job) {
if (!job.retryCount) scores.push((job.timing - job.active) / res.retry)
process.nextTick(function () {
ctx.emit('job', job)
})
})
if (!res.hasMore) return done(null, scores)
}
ctx.getjobs(!res)(getjobs)
}
})
}
Queue.prototype.len = function () {
return thunk.call(this, function (done) {
return this.root.redis.zcard(this.queueKey)(done)
})
}
Queue.prototype.showActive = function () {
return thunk.call(this, function (done) {
var ctx = this
return this.root.redis.hgetall(this.activeQueueKey)(function (err, res) {
if (err) throw err
return Object.keys(res)
.map(function (job) {
var times = res[job].split(':')
return new Job(ctx.name, job, times[0], times[1], times.length - 2)
}).sort(function (a, b) {
return a.timing - b.timing
})
})(done)
})
}
function Job (queue, job, timing, active, retryCount) {
this.queue = queue
this.job = job
this.timing = +timing
this.active = +active
this.retryCount = +retryCount
}
function ScanResult (name, timestamp, res) {
var jobs = res[0]
this.retry = +res[1]
this.hasMore = +res[2]
this.jobs = []
for (var i = 0, l = jobs.length - 2; i < l; i += 3) {
this.jobs.push(new Job(name, jobs[i], jobs[i + 1], timestamp, jobs[i + 2]))
}
}
function slice (args, start) {
start = start || 0
if (start >= args.length) return []
var len = args.length
var ret = Array(len - start)
while (len-- > start) ret[len - start] = args[len]
return ret
}
function validateString (str) {
if (typeof str !== 'string' || !str) throw new TypeError(String(str) + ' is invalid string')
}
| improve regulateFreq method
| index.js | improve regulateFreq method | <ide><path>ndex.js
<ide> return this
<ide> }
<ide>
<add>// x > 0 | 2 - 1 / (1 + x)
<add>// x < 0 | 1 / (1 - x)
<ide> TimedQueue.prototype.regulateFreq = function (factor) {
<del> if (factor < -0.1) this.delay = Math.max(this.delay * (1 + factor), this.interval / 10)
<del> else if (factor > 0.1) this.delay = Math.min(this.delay * (1 + factor), this.interval * 5)
<add> if (factor < -0.05) this.delay = Math.max(this.delay / (1 - factor), this.interval / 10)
<add> else if (factor > 0.05) this.delay = Math.min(this.delay * (2 - 1 / (1 + factor)), this.interval * 5)
<ide> return this
<ide> }
<ide> |
|
Java | mpl-2.0 | ebe35f06d9659b504ca715a1e150a47dd121657a | 0 | GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app | package org.openlca.app.tools.mapping;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.FormDialog;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.openlca.app.M;
import org.openlca.app.db.Database;
import org.openlca.app.tools.mapping.model.DBProvider;
import org.openlca.app.tools.mapping.model.IProvider;
import org.openlca.app.util.Controls;
import org.openlca.app.util.Error;
import org.openlca.app.util.Fn;
import org.openlca.app.util.Labels;
import org.openlca.app.util.UI;
import org.openlca.core.database.FlowDao;
import org.openlca.core.database.IDatabase;
import org.openlca.core.database.LocationDao;
import org.openlca.core.database.ProcessDao;
import org.openlca.core.model.Flow;
import org.openlca.core.model.FlowType;
import org.openlca.core.model.Location;
import org.openlca.core.model.descriptors.ProcessDescriptor;
import org.openlca.io.maps.FlowMapEntry;
import org.openlca.io.maps.FlowRef;
import org.openlca.util.CategoryPathBuilder;
import org.openlca.util.Strings;
class MappingDialog extends FormDialog {
/**
* Opens a dialog for editing the given entry. When the returned status code
* is `OK`, the entry was updated (maybe modified). Otherwise, it is
* unchanged.
*/
static int open(MappingTool tool, FlowMapEntry entry) {
if (tool == null || entry == null)
return CANCEL;
MappingDialog d = new MappingDialog(tool, entry.clone());
int state = d.open();
if (state != OK)
return state;
entry.factor = d.entry.factor;
entry.sourceFlow = d.entry.sourceFlow;
entry.targetFlow = d.entry.targetFlow;
return state;
}
private final MappingTool tool;
private final FlowMapEntry entry;
private IManagedForm mform;
private MappingDialog(MappingTool tool, FlowMapEntry entry) {
super(UI.shell());
this.tool = tool;
this.entry = entry;
if (entry.sourceFlow == null) {
entry.sourceFlow = new FlowRef();
}
if (entry.targetFlow == null) {
entry.targetFlow = new FlowRef();
}
}
@Override
protected void configureShell(Shell shell) {
shell.setText("Flow mapping");
UI.center(UI.shell(), shell);
super.configureShell(shell);
}
@Override
protected void createFormContent(IManagedForm mform) {
this.mform = mform;
FormToolkit tk = mform.getToolkit();
Composite body = mform.getForm().getBody();
UI.gridLayout(body, 1);
Composite comp = tk.createComposite(body);
UI.gridLayout(comp, 1);
UI.gridData(comp, true, false);
// source flow
Fn.with(UI.formLabel(comp, tk, "Source flow"), label -> {
label.setFont(UI.boldFont());
UI.gridData(label, true, false);
});
RefPanel sourcePanel = new RefPanel(entry.sourceFlow, true);
sourcePanel.render(comp, tk);
UI.gridData(tk.createLabel(
comp, "", SWT.SEPARATOR | SWT.HORIZONTAL), true, false);
// target flow
Fn.with(UI.formLabel(comp, tk, "Target flow"), label -> {
label.setFont(UI.boldFont());
UI.gridData(label, true, false);
});
RefPanel targetPanel = new RefPanel(entry.targetFlow, false);
targetPanel.render(comp, tk);
UI.gridData(tk.createLabel(
comp, "", SWT.SEPARATOR | SWT.HORIZONTAL), true, false);
// text with conversion factor
Composite convComp = tk.createComposite(body);
UI.gridLayout(convComp, 3);
UI.gridData(convComp, true, false);
Text convText = UI.formText(convComp, tk, M.ConversionFactor);
convText.setText(Double.toString(entry.factor));
convText.addModifyListener(e -> {
try {
entry.factor = Double.parseDouble(
convText.getText());
} catch (Exception _e) {
}
});
UI.gridData(convText, true, false);
Label unitLabel = UI.formLabel(convComp, tk, "");
Runnable updateUnit = () -> {
String sunit = "?";
String tunit = "?";
if (entry.sourceFlow != null
&& entry.sourceFlow.unit != null
&& entry.sourceFlow.unit.name != null) {
sunit = entry.sourceFlow.unit.name;
}
if (entry.targetFlow != null
&& entry.targetFlow.unit != null
&& entry.targetFlow.unit.name != null) {
tunit = entry.targetFlow.unit.name;
}
unitLabel.setText(sunit + "/" + tunit);
unitLabel.getParent().pack();
};
updateUnit.run();
sourcePanel.onChange = updateUnit;
targetPanel.onChange = updateUnit;
}
private class RefPanel {
final FlowRef ref;
final boolean forSource;
Hyperlink flowLink;
Label categoryLabel;
Label propertyLabel;
Label unitLabel;
ProviderCombo providerCombo;
Runnable onChange;
RefPanel(FlowRef ref, boolean forSource) {
this.ref = ref;
this.forSource = forSource;
}
void render(Composite parent, FormToolkit tk) {
Composite comp = tk.createComposite(parent);
UI.gridLayout(comp, 2, 10, 5);
UI.gridData(comp, true, false);
UI.formLabel(comp, tk, M.Flow);
flowLink = UI.formLink(comp, tk, "");
Controls.onClick(flowLink, _e -> {
IProvider p = forSource
? tool.sourceSystem
: tool.targetSystem;
if (p == null) {
Error.showBox("Cannot select flow",
"No data source for flows connected");
return;
}
FlowRefDialog.open(p, opt -> {
if (!opt.isPresent())
return;
updateWith(opt.get());
});
});
UI.formLabel(comp, tk, M.Category);
categoryLabel = UI.formLabel(comp, tk, "");
UI.formLabel(comp, tk, M.FlowProperty);
propertyLabel = UI.formLabel(comp, tk, "");
UI.formLabel(comp, tk, M.Unit);
unitLabel = UI.formLabel(comp, tk, "");
// the provider link
if (!forSource && tool.targetSystem instanceof DBProvider) {
Combo combo = UI.formCombo(comp, tk, M.Provider);
UI.gridData(combo, false, false).widthHint = 400;
this.providerCombo = new ProviderCombo(ref, combo);
}
updateLabels();
}
private void updateWith(FlowRef newRef) {
if (newRef == null) {
ref.flow = null;
ref.flowCategory = null;
ref.flowLocation = null;
ref.property = null;
ref.unit = null;
if (providerCombo != null) {
providerCombo.update();
}
return;
}
ref.flow = newRef.flow;
ref.flowCategory = newRef.flowCategory;
ref.flowLocation = newRef.flowLocation;
ref.property = newRef.property;
ref.unit = newRef.unit;
updateLabels();
if (providerCombo != null) {
providerCombo.update();
}
if (onChange != null) {
onChange.run();
}
}
private void updateLabels() {
int maxLen = 80;
// flow name
if (ref.flow == null) {
flowLink.setText("- none -");
} else {
String t = ref.flow.name;
if (t == null) {
t = ref.flow.refId;
}
if (t == null) {
t = "?";
}
if (Strings.notEmpty(ref.flowLocation)) {
t += " - " + ref.flowLocation;
}
flowLink.setText(Strings.cut(t, maxLen));
flowLink.setToolTipText(t);
}
// category path
if (Strings.nullOrEmpty(ref.flowCategory)) {
categoryLabel.setText("");
} else {
categoryLabel.setText(
Strings.cutLeft(ref.flowCategory, maxLen));
categoryLabel.setToolTipText(ref.flowCategory);
}
// flow property
if (ref.property == null || ref.property.name == null) {
propertyLabel.setText("");
} else {
propertyLabel.setText(ref.property.name);
propertyLabel.setToolTipText(ref.property.name);
}
// unit
if (ref.unit == null || ref.unit.name == null) {
unitLabel.setText("");
} else {
unitLabel.setText(ref.unit.name);
unitLabel.setToolTipText(ref.unit.name);
}
flowLink.getParent().getParent().pack();
flowLink.getParent().pack();
mform.reflow(true);
}
}
private static class ProviderCombo {
private final FlowRef ref;
private final Combo combo;
private final ArrayList<ProcessDescriptor> providers = new ArrayList<>();
ProviderCombo(FlowRef ref, Combo combo) {
this.ref = ref;
this.combo = combo;
Controls.onSelect(combo, e -> {
int i = combo.getSelectionIndex() - 1;
if (i < 0 || i >= providers.size()) {
setProvider(null);
} else {
setProvider(providers.get(i));
}
combo.setToolTipText(combo.getItems()[i + 1]);
});
update();
}
void update() {
if (ref.flow == null
|| ref.flow.refId == null
|| ref.flow.flowType == FlowType.ELEMENTARY_FLOW) {
providers.clear();
combo.setItems();
combo.setEnabled(false);
setProvider(null);
return;
}
IDatabase db = Database.get();
combo.setEnabled(true);
// collect providers
providers.clear();
long flowID = ref.flow.id;
FlowDao fdao = new FlowDao(db);
if (flowID == 0L) {
Flow flow = fdao.getForRefId(ref.flow.refId);
flowID = flow != null ? flow.id : 0L;
}
if (flowID > 0L) {
Set<Long> ids = ref.flow.flowType == FlowType.WASTE_FLOW
? fdao.getWhereInput(flowID)
: fdao.getWhereOutput(flowID);
providers.addAll(new ProcessDao(db).getDescriptors(ids));
Collections.sort(providers,
(p1, p2) -> Strings.compare(
Labels.getDisplayName(p1),
Labels.getDisplayName(p2)));
}
// fill the provider combo
String[] items = new String[providers.size() + 1];
items[0] = "- none -";
int selected = 0;
for (int i = 0; i < providers.size(); i++) {
ProcessDescriptor p = providers.get(i);
items[i + 1] = Labels.getDisplayName(p);
if (ref.provider != null
&& Objects.equals(p.refId, ref.provider.refId)) {
selected = i + 1;
}
}
combo.setItems(items);
combo.setToolTipText(items[selected]);
combo.select(selected);
if (ref.provider != null && selected == 0) {
// the provider is not in the database
// => we set it to null
setProvider(null);
}
}
private void setProvider(ProcessDescriptor p) {
if (p == null) {
ref.provider = null;
ref.providerCategory = null;
ref.providerLocation = null;
return;
}
ref.provider = p;
if (p.category == null) {
ref.providerCategory = "";
} else {
ref.providerCategory = new CategoryPathBuilder(
Database.get()).build(p.category);
}
if (p.location == null) {
ref.providerLocation = "";
} else {
Location loc = new LocationDao(
Database.get()).getForId(p.location);
ref.providerLocation = loc != null
? loc.code
: "";
}
}
}
}
| olca-app/src/org/openlca/app/tools/mapping/MappingDialog.java | package org.openlca.app.tools.mapping;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.FormDialog;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.openlca.app.M;
import org.openlca.app.db.Database;
import org.openlca.app.tools.mapping.model.DBProvider;
import org.openlca.app.tools.mapping.model.IProvider;
import org.openlca.app.util.Controls;
import org.openlca.app.util.Error;
import org.openlca.app.util.Fn;
import org.openlca.app.util.Labels;
import org.openlca.app.util.UI;
import org.openlca.core.database.FlowDao;
import org.openlca.core.database.IDatabase;
import org.openlca.core.database.LocationDao;
import org.openlca.core.database.ProcessDao;
import org.openlca.core.model.Flow;
import org.openlca.core.model.FlowType;
import org.openlca.core.model.Location;
import org.openlca.core.model.descriptors.ProcessDescriptor;
import org.openlca.io.maps.FlowMapEntry;
import org.openlca.io.maps.FlowRef;
import org.openlca.util.CategoryPathBuilder;
import org.openlca.util.Strings;
class MappingDialog extends FormDialog {
/**
* Opens a dialog for editing the given entry. When the returned status code
* is `OK`, the entry was updated (maybe modified). Otherwise, it is
* unchanged.
*/
static int open(MappingTool tool, FlowMapEntry entry) {
if (tool == null || entry == null)
return CANCEL;
MappingDialog d = new MappingDialog(tool, entry.clone());
int state = d.open();
if (state != OK)
return state;
entry.factor = d.entry.factor;
entry.sourceFlow = d.entry.sourceFlow;
entry.targetFlow = d.entry.targetFlow;
return state;
}
private final MappingTool tool;
private final FlowMapEntry entry;
private IManagedForm mform;
private MappingDialog(MappingTool tool, FlowMapEntry entry) {
super(UI.shell());
this.tool = tool;
this.entry = entry;
if (entry.sourceFlow == null) {
entry.sourceFlow = new FlowRef();
}
if (entry.targetFlow == null) {
entry.targetFlow = new FlowRef();
}
}
@Override
protected void createFormContent(IManagedForm mform) {
this.mform = mform;
FormToolkit tk = mform.getToolkit();
Composite body = mform.getForm().getBody();
UI.gridLayout(body, 1);
Composite comp = tk.createComposite(body);
UI.gridLayout(comp, 2).makeColumnsEqualWidth = true;
Fn.with(UI.formLabel(comp, tk, "Source flow"), label -> {
label.setFont(UI.boldFont());
UI.gridData(label, true, false);
});
Fn.with(UI.formLabel(comp, tk, "Target flow"), label -> {
label.setFont(UI.boldFont());
UI.gridData(label, true, false);
});
RefPanel sourcePanel = new RefPanel(entry.sourceFlow, true);
sourcePanel.render(comp, tk);
RefPanel targetPanel = new RefPanel(entry.targetFlow, false);
targetPanel.render(comp, tk);
// text with conversion factor
Composite convComp = tk.createComposite(body);
UI.gridLayout(convComp, 3);
Text convText = UI.formText(convComp, tk, M.ConversionFactor);
convText.setText(Double.toString(entry.factor));
convText.addModifyListener(e -> {
try {
entry.factor = Double.parseDouble(
convText.getText());
} catch (Exception _e) {
}
});
UI.gridData(convText, false, false).widthHint = 200;
Label unitLabel = UI.formLabel(convComp, tk, "");
Runnable updateUnit = () -> {
String sunit = "?";
String tunit = "?";
if (entry.sourceFlow != null
&& entry.sourceFlow.unit != null
&& entry.sourceFlow.unit.name != null) {
sunit = entry.sourceFlow.unit.name;
}
if (entry.targetFlow != null
&& entry.targetFlow.unit != null
&& entry.targetFlow.unit.name != null) {
tunit = entry.targetFlow.unit.name;
}
unitLabel.setText(sunit + "/" + tunit);
unitLabel.getParent().pack();
};
updateUnit.run();
sourcePanel.onChange = updateUnit;
targetPanel.onChange = updateUnit;
}
@Override
protected Point getInitialSize() {
return new Point(800, 450);
}
private class RefPanel {
final FlowRef ref;
final boolean forSource;
Hyperlink flowLink;
Label categoryLabel;
Label propertyLabel;
Label unitLabel;
ProviderCombo providerCombo;
Runnable onChange;
RefPanel(FlowRef ref, boolean forSource) {
this.ref = ref;
this.forSource = forSource;
}
void render(Composite parent, FormToolkit tk) {
Composite comp = tk.createComposite(parent);
UI.gridLayout(comp, 2, 15, 10);
UI.formLabel(comp, tk, M.Flow);
flowLink = UI.formLink(comp, tk, "");
Controls.onClick(flowLink, _e -> {
IProvider p = forSource
? tool.sourceSystem
: tool.targetSystem;
if (p == null) {
Error.showBox("Cannot select flow",
"No data source for flows connected");
return;
}
FlowRefDialog.open(p, opt -> {
if (!opt.isPresent())
return;
updateWith(opt.get());
});
});
UI.formLabel(comp, tk, M.Category);
categoryLabel = UI.formLabel(comp, tk, "");
UI.formLabel(comp, tk, M.FlowProperty);
propertyLabel = UI.formLabel(comp, tk, "");
UI.formLabel(comp, tk, M.Unit);
unitLabel = UI.formLabel(comp, tk, "");
// the provider link
if (!forSource && tool.targetSystem instanceof DBProvider) {
Combo combo = UI.formCombo(comp, tk, M.Provider);
UI.gridData(combo, false, false).widthHint = 220;
this.providerCombo = new ProviderCombo(ref, combo);
} else {
UI.filler(comp, tk);
UI.filler(comp, tk);
}
updateLabels();
}
private void updateWith(FlowRef newRef) {
if (newRef == null) {
ref.flow = null;
ref.flowCategory = null;
ref.flowLocation = null;
ref.property = null;
ref.unit = null;
if (providerCombo != null) {
providerCombo.update();
}
return;
}
ref.flow = newRef.flow;
ref.flowCategory = newRef.flowCategory;
ref.flowLocation = newRef.flowLocation;
ref.property = newRef.property;
ref.unit = newRef.unit;
updateLabels();
if (providerCombo != null) {
providerCombo.update();
}
if (onChange != null) {
onChange.run();
}
}
private void updateLabels() {
int maxLen = 40;
// flow name
if (ref.flow == null) {
flowLink.setText("- none -");
} else {
String t = ref.flow.name;
if (t == null) {
t = ref.flow.refId;
}
if (t == null) {
t = "?";
}
if (Strings.notEmpty(ref.flowLocation)) {
t += " - " + ref.flowLocation;
}
flowLink.setText(Strings.cut(t, maxLen));
flowLink.setToolTipText(t);
}
// category path
if (Strings.nullOrEmpty(ref.flowCategory)) {
categoryLabel.setText("");
} else {
categoryLabel.setText(
Strings.cutLeft(ref.flowCategory, maxLen));
categoryLabel.setToolTipText(ref.flowCategory);
}
// flow property
if (ref.property == null || ref.property.name == null) {
propertyLabel.setText("");
} else {
propertyLabel.setText(ref.property.name);
propertyLabel.setToolTipText(ref.property.name);
}
// unit
if (ref.unit == null || ref.unit.name == null) {
unitLabel.setText("");
} else {
unitLabel.setText(ref.unit.name);
unitLabel.setToolTipText(ref.unit.name);
}
flowLink.getParent().getParent().pack();
flowLink.getParent().pack();
mform.reflow(true);
}
}
private static class ProviderCombo {
private final FlowRef ref;
private final Combo combo;
private final ArrayList<ProcessDescriptor> providers = new ArrayList<>();
ProviderCombo(FlowRef ref, Combo combo) {
this.ref = ref;
this.combo = combo;
Controls.onSelect(combo, e -> {
int i = combo.getSelectionIndex() - 1;
if (i < 0 || i >= providers.size()) {
setProvider(null);
} else {
setProvider(providers.get(i));
}
combo.setToolTipText(combo.getItems()[i + 1]);
});
update();
}
void update() {
if (ref.flow == null
|| ref.flow.refId == null
|| ref.flow.flowType == FlowType.ELEMENTARY_FLOW) {
providers.clear();
combo.setItems();
combo.setEnabled(false);
setProvider(null);
return;
}
IDatabase db = Database.get();
combo.setEnabled(true);
// collect providers
providers.clear();
long flowID = ref.flow.id;
FlowDao fdao = new FlowDao(db);
if (flowID == 0L) {
Flow flow = fdao.getForRefId(ref.flow.refId);
flowID = flow != null ? flow.id : 0L;
}
if (flowID > 0L) {
Set<Long> ids = ref.flow.flowType == FlowType.WASTE_FLOW
? fdao.getWhereInput(flowID)
: fdao.getWhereOutput(flowID);
providers.addAll(new ProcessDao(db).getDescriptors(ids));
Collections.sort(providers,
(p1, p2) -> Strings.compare(
Labels.getDisplayName(p1),
Labels.getDisplayName(p2)));
}
// fill the provider combo
String[] items = new String[providers.size() + 1];
items[0] = "- none -";
int selected = 0;
for (int i = 0; i < providers.size(); i++) {
ProcessDescriptor p = providers.get(i);
items[i + 1] = Labels.getDisplayName(p);
if (ref.provider != null
&& Objects.equals(p.refId, ref.provider.refId)) {
selected = i + 1;
}
}
combo.setItems(items);
combo.setToolTipText(items[selected]);
combo.select(selected);
if (ref.provider != null && selected == 0) {
// the provider is not in the database
// => we set it to null
setProvider(null);
}
}
private void setProvider(ProcessDescriptor p) {
if (p == null) {
ref.provider = null;
ref.providerCategory = null;
ref.providerLocation = null;
return;
}
ref.provider = p;
if (p.category == null) {
ref.providerCategory = "";
} else {
ref.providerCategory = new CategoryPathBuilder(
Database.get()).build(p.category);
}
if (p.location == null) {
ref.providerLocation = "";
} else {
Location loc = new LocationDao(
Database.get()).getForId(p.location);
ref.providerLocation = loc != null
? loc.code
: "";
}
}
}
}
| this improves the design of the mapping
dialog a bit. still, it is not possible
to control the size of the combo box
dynamically ... | olca-app/src/org/openlca/app/tools/mapping/MappingDialog.java | this improves the design of the mapping | <ide><path>lca-app/src/org/openlca/app/tools/mapping/MappingDialog.java
<ide> import java.util.Objects;
<ide> import java.util.Set;
<ide>
<del>import org.eclipse.swt.graphics.Point;
<add>import org.eclipse.swt.SWT;
<ide> import org.eclipse.swt.widgets.Combo;
<ide> import org.eclipse.swt.widgets.Composite;
<ide> import org.eclipse.swt.widgets.Label;
<add>import org.eclipse.swt.widgets.Shell;
<ide> import org.eclipse.swt.widgets.Text;
<ide> import org.eclipse.ui.forms.FormDialog;
<ide> import org.eclipse.ui.forms.IManagedForm;
<ide> }
<ide>
<ide> @Override
<add> protected void configureShell(Shell shell) {
<add> shell.setText("Flow mapping");
<add> UI.center(UI.shell(), shell);
<add> super.configureShell(shell);
<add> }
<add>
<add> @Override
<ide> protected void createFormContent(IManagedForm mform) {
<ide> this.mform = mform;
<ide> FormToolkit tk = mform.getToolkit();
<ide> Composite body = mform.getForm().getBody();
<ide> UI.gridLayout(body, 1);
<ide> Composite comp = tk.createComposite(body);
<del> UI.gridLayout(comp, 2).makeColumnsEqualWidth = true;
<del>
<add> UI.gridLayout(comp, 1);
<add> UI.gridData(comp, true, false);
<add>
<add> // source flow
<ide> Fn.with(UI.formLabel(comp, tk, "Source flow"), label -> {
<ide> label.setFont(UI.boldFont());
<ide> UI.gridData(label, true, false);
<ide> });
<add> RefPanel sourcePanel = new RefPanel(entry.sourceFlow, true);
<add> sourcePanel.render(comp, tk);
<add> UI.gridData(tk.createLabel(
<add> comp, "", SWT.SEPARATOR | SWT.HORIZONTAL), true, false);
<add>
<add> // target flow
<ide> Fn.with(UI.formLabel(comp, tk, "Target flow"), label -> {
<ide> label.setFont(UI.boldFont());
<ide> UI.gridData(label, true, false);
<ide> });
<del>
<del> RefPanel sourcePanel = new RefPanel(entry.sourceFlow, true);
<del> sourcePanel.render(comp, tk);
<ide> RefPanel targetPanel = new RefPanel(entry.targetFlow, false);
<ide> targetPanel.render(comp, tk);
<add> UI.gridData(tk.createLabel(
<add> comp, "", SWT.SEPARATOR | SWT.HORIZONTAL), true, false);
<ide>
<ide> // text with conversion factor
<ide> Composite convComp = tk.createComposite(body);
<ide> UI.gridLayout(convComp, 3);
<add> UI.gridData(convComp, true, false);
<ide> Text convText = UI.formText(convComp, tk, M.ConversionFactor);
<ide> convText.setText(Double.toString(entry.factor));
<ide> convText.addModifyListener(e -> {
<ide> }
<ide> });
<ide>
<del> UI.gridData(convText, false, false).widthHint = 200;
<add> UI.gridData(convText, true, false);
<ide> Label unitLabel = UI.formLabel(convComp, tk, "");
<ide> Runnable updateUnit = () -> {
<ide> String sunit = "?";
<ide> targetPanel.onChange = updateUnit;
<ide> }
<ide>
<del> @Override
<del> protected Point getInitialSize() {
<del> return new Point(800, 450);
<del> }
<del>
<ide> private class RefPanel {
<ide>
<ide> final FlowRef ref;
<ide>
<ide> void render(Composite parent, FormToolkit tk) {
<ide> Composite comp = tk.createComposite(parent);
<del> UI.gridLayout(comp, 2, 15, 10);
<add> UI.gridLayout(comp, 2, 10, 5);
<add> UI.gridData(comp, true, false);
<ide>
<ide> UI.formLabel(comp, tk, M.Flow);
<ide> flowLink = UI.formLink(comp, tk, "");
<ide> // the provider link
<ide> if (!forSource && tool.targetSystem instanceof DBProvider) {
<ide> Combo combo = UI.formCombo(comp, tk, M.Provider);
<del> UI.gridData(combo, false, false).widthHint = 220;
<add> UI.gridData(combo, false, false).widthHint = 400;
<ide> this.providerCombo = new ProviderCombo(ref, combo);
<del> } else {
<del> UI.filler(comp, tk);
<del> UI.filler(comp, tk);
<ide> }
<ide> updateLabels();
<ide> }
<ide> }
<ide>
<ide> private void updateLabels() {
<del> int maxLen = 40;
<add> int maxLen = 80;
<ide>
<ide> // flow name
<ide> if (ref.flow == null) { |
|
Java | apache-2.0 | b4e7220e9232f627b2ce6b18979ee86cdaeeb6d6 | 0 | Ooppa/iot-industrial-internet,Ooppa/iot-industrial-internet,Ooppa/iot-industrial-internet,Ooppa/iot-industrial-internet | /*
* IoT - Industrial Internet Framework
* Apache License Version 2.0, January 2004
* Released as a part of Helsinki University
* Software Engineering Lab in summer 2015
*/
package fi.iot.iiframework.errors;
public enum ErrorSeverity {
NONE(0, "NONE"),
NOTIFICATION(1, "NOTIFICATION"),
LOW(2, "LOW"),
MEDIUM(3, "MEDIUM"),
HIGH(4, "HIGH"),
FATAL(5, "FATAL");
private final int severity;
private final String id;
ErrorSeverity(int severity, String id) {
this.severity = severity;
this.id = id;
}
public int getSeverity() {
return this.severity;
}
public String getId() {
return id;
}
/**
* Returns ErrorSeverity from the given ID.
*
* @param id Severity identifier
* @return ErrorSeverity
*/
public static ErrorSeverity getType(String id) {
ErrorSeverity[] values = ErrorSeverity.values();
for (ErrorSeverity value : values) {
if (value.getId().equals(id)) {
return value;
}
}
return ErrorSeverity.NONE;
}
}
| iot-industrial-internet/src/main/java/fi/iot/iiframework/errors/ErrorSeverity.java | /*
* IoT - Industrial Internet Framework
* Apache License Version 2.0, January 2004
* Released as a part of Helsinki University
* Software Engineering Lab in summer 2015
*/
package fi.iot.iiframework.errors;
public enum ErrorSeverity {
NONE(0, "NONE"),
NOTIFICATION(1, "NOTIFICATION"),
LOW(2, "LOW"),
MEDIUM(3, "MEDIUM"),
HIGH(4, "HIGH"),
FATAL(5, "FATAL");
private final int severity;
private final String id;
ErrorSeverity(int severity, String id) {
this.severity = severity;
this.id = id;
}
public int getSeverity() {
return this.severity;
}
public String getId() {
return id;
}
public static ErrorSeverity getType(String id) {
ErrorSeverity[] values = ErrorSeverity.values();
for (ErrorSeverity value : values) {
if (value.getId().equals(id)) {
return value;
}
}
return ErrorSeverity.NONE;
}
}
| JavaDoc for ErrorSeverity
| iot-industrial-internet/src/main/java/fi/iot/iiframework/errors/ErrorSeverity.java | JavaDoc for ErrorSeverity | <ide><path>ot-industrial-internet/src/main/java/fi/iot/iiframework/errors/ErrorSeverity.java
<ide> return id;
<ide> }
<ide>
<add> /**
<add> * Returns ErrorSeverity from the given ID.
<add> *
<add> * @param id Severity identifier
<add> * @return ErrorSeverity
<add> */
<ide> public static ErrorSeverity getType(String id) {
<ide> ErrorSeverity[] values = ErrorSeverity.values();
<ide> |
|
Java | mit | error: pathspec 'ontrack-service/src/main/java/net/nemerosa/ontrack/service/security/JdbcConfidentialStore.java' did not match any file(s) known to git
| 60077feeb479b5968bb73bb08a39623d5adef972 | 1 | nemerosa/ontrack,flesire/ontrack,flesire/ontrack,flesire/ontrack,nemerosa/ontrack,nemerosa/ontrack,nemerosa/ontrack,nemerosa/ontrack,flesire/ontrack,flesire/ontrack | package net.nemerosa.ontrack.service.security;
import lombok.Data;
import net.nemerosa.ontrack.model.security.AbstractConfidentialStore;
import net.nemerosa.ontrack.model.support.OntrackConfigProperties;
import net.nemerosa.ontrack.model.support.StorageService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* Storing the keys in the database.
* <p>
* This is easy to setup but is NOT secure.
*/
@Component
@ConditionalOnProperty(name = OntrackConfigProperties.KEY_STORE, havingValue = "jdbc")
public class JdbcConfidentialStore extends AbstractConfidentialStore {
private final StorageService storageService;
@Autowired
public JdbcConfidentialStore(StorageService storageService) {
this.storageService = storageService;
LoggerFactory.getLogger(JdbcConfidentialStore.class).info(
"[key-store] Using JDBC based key store"
);
}
@Override
public void store(String key, byte[] payload) throws IOException {
storageService.store(
JdbcConfidentialStore.class.getSimpleName(),
key,
new Key(payload)
);
}
@Override
public byte[] load(String key) throws IOException {
return storageService.retrieve(
JdbcConfidentialStore.class.getSimpleName(),
key,
Key.class
)
.map(Key::getPayload)
.orElse(null);
}
@Data
public static class Key {
private final byte[] payload;
}
}
| ontrack-service/src/main/java/net/nemerosa/ontrack/service/security/JdbcConfidentialStore.java | #481 JDBC key store
| ontrack-service/src/main/java/net/nemerosa/ontrack/service/security/JdbcConfidentialStore.java | #481 JDBC key store | <ide><path>ntrack-service/src/main/java/net/nemerosa/ontrack/service/security/JdbcConfidentialStore.java
<add>package net.nemerosa.ontrack.service.security;
<add>
<add>import lombok.Data;
<add>import net.nemerosa.ontrack.model.security.AbstractConfidentialStore;
<add>import net.nemerosa.ontrack.model.support.OntrackConfigProperties;
<add>import net.nemerosa.ontrack.model.support.StorageService;
<add>import org.slf4j.LoggerFactory;
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
<add>import org.springframework.stereotype.Component;
<add>
<add>import java.io.IOException;
<add>
<add>/**
<add> * Storing the keys in the database.
<add> * <p>
<add> * This is easy to setup but is NOT secure.
<add> */
<add>@Component
<add>@ConditionalOnProperty(name = OntrackConfigProperties.KEY_STORE, havingValue = "jdbc")
<add>public class JdbcConfidentialStore extends AbstractConfidentialStore {
<add>
<add> private final StorageService storageService;
<add>
<add> @Autowired
<add> public JdbcConfidentialStore(StorageService storageService) {
<add> this.storageService = storageService;
<add> LoggerFactory.getLogger(JdbcConfidentialStore.class).info(
<add> "[key-store] Using JDBC based key store"
<add> );
<add> }
<add>
<add> @Override
<add> public void store(String key, byte[] payload) throws IOException {
<add> storageService.store(
<add> JdbcConfidentialStore.class.getSimpleName(),
<add> key,
<add> new Key(payload)
<add> );
<add> }
<add>
<add> @Override
<add> public byte[] load(String key) throws IOException {
<add> return storageService.retrieve(
<add> JdbcConfidentialStore.class.getSimpleName(),
<add> key,
<add> Key.class
<add> )
<add> .map(Key::getPayload)
<add> .orElse(null);
<add> }
<add>
<add> @Data
<add> public static class Key {
<add> private final byte[] payload;
<add> }
<add>} |
|
Java | bsd-3-clause | 8fdd27fb08bd8bea4d7e476730624dac5b0ac4c9 | 0 | asamgir/openspecimen,asamgir/openspecimen,krishagni/openspecimen,asamgir/openspecimen,krishagni/openspecimen,krishagni/openspecimen | /**
* <p>Title: SpecimenCollectionGroupAction Class>
* <p>Description: SpecimenCollectionGroupAction initializes the fields in the
* New Specimen Collection Group page.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Ajay Sharma
* @version 1.00
*/
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.action.annotations.AnnotationConstants;
import edu.wustl.catissuecore.actionForm.SpecimenCollectionGroupForm;
import edu.wustl.catissuecore.bizlogic.AnnotationUtil;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.CollectionProtocolRegistrationBizLogic;
import edu.wustl.catissuecore.bizlogic.IdentifiedSurgicalPathologyReportBizLogic;
import edu.wustl.catissuecore.bizlogic.SpecimenCollectionGroupBizLogic;
import edu.wustl.catissuecore.bizlogic.UserBizLogic;
import edu.wustl.catissuecore.domain.CollectionEventParameters;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolEvent;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.ConsentTier;
import edu.wustl.catissuecore.domain.ConsentTierResponse;
import edu.wustl.catissuecore.domain.ConsentTierStatus;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.domain.ParticipantMedicalIdentifier;
import edu.wustl.catissuecore.domain.ReceivedEventParameters;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.SpecimenCollectionRequirementGroup;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.domain.pathology.IdentifiedSurgicalPathologyReport;
import edu.wustl.catissuecore.util.CatissueCoreCacheManager;
import edu.wustl.catissuecore.util.EventsUtil;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.DefaultValueManager;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.common.action.SecureAction;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.CDEBizLogic;
import edu.wustl.common.bizlogic.IBizLogic;
import edu.wustl.common.cde.CDE;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.logger.Logger;
/**
* SpecimenCollectionGroupAction initializes the fields in the
* New Specimen Collection Group page.
* @author ajay_sharma
*/
public class SpecimenCollectionGroupAction extends SecureAction
{
/**
* Overrides the execute method of Action class.
* @param mapping object of ActionMapping
* @param form object of ActionForm
* @param request object of HttpServletRequest
* @param response object of HttpServletResponse
* @throws Exception generic exception
*/
public ActionForward executeSecureAction(ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response)
throws Exception
{
//changes made by Baljeet
String treeRefresh = request.getParameter("refresh");
request.setAttribute("refresh", treeRefresh);
SpecimenCollectionGroupForm specimenCollectionGroupForm = (SpecimenCollectionGroupForm) form;
IBizLogic bizLogicObj = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC);
Logger.out.debug("SCGA : " + specimenCollectionGroupForm.getId());
String nodeId = null;
/**
* Bug id : 4213
* Patch id : 4213_2
* Description : getting parameters from request and keeping them in seesion to keep the node in tree selected.
*/
if (request.getParameter("clickedNodeId") != null)
{
nodeId = request.getParameter("clickedNodeId");
request.getSession().setAttribute("nodeId", nodeId);
}
// set the menu selection
request.setAttribute(Constants.MENU_SELECTED, "14");
//pageOf and operation attributes required for Advance Query Object view.
String pageOf = request.getParameter(Constants.PAGEOF);
//Gets the value of the operation parameter.
String operation = (String) request.getParameter(Constants.OPERATION);
//Sets the operation attribute to be used in the Edit/View Specimen Collection Group Page in Advance Search Object View.
request.setAttribute(Constants.OPERATION, operation);
if (operation.equalsIgnoreCase(Constants.ADD))
{
specimenCollectionGroupForm.setId(0);
Logger.out.debug("SCGA : set to 0 " + specimenCollectionGroupForm.getId());
}
boolean isOnChange = false;
String str = request.getParameter("isOnChange");
if (str != null)
{
if (str.equals("true"))
{
isOnChange = true;
}
}
//For Consent Tracking (Virender Mehta) - Start
//If radioButtonSelected = 1 then selected radio button is for Participant
//If radioButtonSelected = 2 then selected radio button is for Protocol Participant Identifier
int radioButtonSelected = 1;
//Id of Selected Participant or Protocol Participant Identifier
String selectedParticipantOrPPIdentifier_id = null;
// Radio button for Protocol Participant Identifier or Participant
String radioButtonSelectedForType = null;
String selectedCollectionProtocol_id = String.valueOf(specimenCollectionGroupForm.getCollectionProtocolId());
if (selectedCollectionProtocol_id.equalsIgnoreCase(Constants.SELECTED_COLLECTION_PROTOCOL_ID))
{
Map forwardToHashMap = (Map) request.getAttribute(Constants.FORWARD_TO_HASHMAP);
if (forwardToHashMap != null)
{
selectedCollectionProtocol_id = forwardToHashMap.get(Constants.COLLECTION_PROTOCOL_ID).toString();
selectedParticipantOrPPIdentifier_id = forwardToHashMap.get(Constants.PARTICIPANT_ID).toString();
radioButtonSelectedForType = Constants.PARTICIPANT_ID;
if (selectedParticipantOrPPIdentifier_id.equals("0"))
{
selectedParticipantOrPPIdentifier_id = forwardToHashMap.get(Constants.PARTICIPANT_PROTOCOL_ID).toString();
radioButtonSelectedForType = Constants.PARTICIPANT_PROTOCOL_ID;
}
}
}
else
{
radioButtonSelected = (int) specimenCollectionGroupForm.getRadioButtonForParticipant();
if (radioButtonSelected == 1)
{
selectedParticipantOrPPIdentifier_id = Long.toString(specimenCollectionGroupForm.getParticipantId());
radioButtonSelectedForType = Constants.PARTICIPANT_ID;
}
else
{
selectedParticipantOrPPIdentifier_id = specimenCollectionGroupForm.getProtocolParticipantIdentifier();
radioButtonSelectedForType = Constants.PARTICIPANT_PROTOCOL_ID;
}
}
CollectionProtocolRegistration collectionProtocolRegistration = null;
if (selectedParticipantOrPPIdentifier_id != null && !(selectedParticipantOrPPIdentifier_id.equalsIgnoreCase("0")))
{
//Get CollectionprotocolRegistration Object
collectionProtocolRegistration = getcollectionProtocolRegistrationObj(selectedParticipantOrPPIdentifier_id,
selectedCollectionProtocol_id, radioButtonSelectedForType);
}
else if (specimenCollectionGroupForm.getId() != 0)
{
//Get CollectionprotocolRegistration Object
SpecimenCollectionGroupBizLogic specimenCollectiongroupBizLogic = (SpecimenCollectionGroupBizLogic) BizLogicFactory.getInstance()
.getBizLogic(Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
collectionProtocolRegistration = (CollectionProtocolRegistration) specimenCollectiongroupBizLogic.retrieveAttribute(
SpecimenCollectionGroup.class.getName(), specimenCollectionGroupForm.getId(), "collectionProtocolRegistration");
}
User witness = null;
if (collectionProtocolRegistration.getId() != null)
{
witness = (User) bizLogicObj.retrieveAttribute(CollectionProtocolRegistration.class.getName(), collectionProtocolRegistration.getId(),
"consentWitness");
}
//User witness= userObj.getConsentWitness();
//Resolved Lazy
if (witness == null || witness.getFirstName() == null)
{
String witnessName = "";
specimenCollectionGroupForm.setWitnessName(witnessName);
}
else
{
String witnessFullName = witness.getLastName() + ", " + witness.getFirstName();
specimenCollectionGroupForm.setWitnessName(witnessFullName);
}
String getConsentDate = Utility
.parseDateToString(collectionProtocolRegistration.getConsentSignatureDate(), Constants.DATE_PATTERN_MM_DD_YYYY);
specimenCollectionGroupForm.setConsentDate(getConsentDate);
String getSignedConsentURL = Utility.toString(collectionProtocolRegistration.getSignedConsentDocumentURL());
specimenCollectionGroupForm.setSignedConsentUrl(getSignedConsentURL);
//Set witnessName,ConsentDate and SignedConsentURL
//Resolved Lazy ----collectionProtocolRegistration.getConsentTierResponseCollection()
Collection consentTierResponseCollection = (Collection) bizLogicObj.retrieveAttribute(CollectionProtocolRegistration.class.getName(),
collectionProtocolRegistration.getId(), "elements(consentTierResponseCollection)");
Set participantResponseSet = (Set) consentTierResponseCollection;
List participantResponseList = new ArrayList(participantResponseSet);
if (operation.equalsIgnoreCase(Constants.ADD))
{
ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
if (errors == null)
{
String protocolEventID = request.getParameter(Constants.PROTOCOL_EVENT_ID);
if (protocolEventID == null || protocolEventID.equalsIgnoreCase(Constants.FALSE))
{
Map tempMap = prepareConsentMap(participantResponseList);
specimenCollectionGroupForm.setConsentResponseForScgValues(tempMap);
}
}
specimenCollectionGroupForm.setConsentTierCounter(participantResponseList.size());
}
else
{
String scgID = String.valueOf(specimenCollectionGroupForm.getId());
SpecimenCollectionGroup specimenCollectionGroup = getSCGObj(scgID);
//List added for grid
List specimenDetails = new ArrayList();
getSpecimenDetails(specimenCollectionGroup, specimenDetails);
List columnList = columnNames();
//Resolved Lazy
//Collection consentResponse = specimenCollectionGroup.getCollectionProtocolRegistration().getConsentTierResponseCollection();
//Collection consentResponseStatuslevel= specimenCollectionGroup.getConsentTierStatusCollection();
Collection consentResponse = (Collection) bizLogicObj.retrieveAttribute(SpecimenCollectionGroup.class.getName(), specimenCollectionGroup
.getId(), "elements(collectionProtocolRegistration.consentTierResponseCollection)");
Collection consentResponseStatuslevel = (Collection) bizLogicObj.retrieveAttribute(SpecimenCollectionGroup.class.getName(),
specimenCollectionGroup.getId(), "elements(consentTierStatusCollection)");
Map tempMap = prepareSCGResponseMap(consentResponseStatuslevel, consentResponse);
specimenCollectionGroupForm.setConsentResponseForScgValues(tempMap);
specimenCollectionGroupForm.setConsentTierCounter(participantResponseList.size());
HttpSession session = request.getSession();
session.setAttribute(Constants.SPECIMEN_LIST, specimenDetails);
session.setAttribute(Constants.COLUMNLIST, columnList);
}
List specimenCollectionGroupResponseList = Utility.responceList(operation);
request.setAttribute(Constants.LIST_OF_SPECIMEN_COLLECTION_GROUP, specimenCollectionGroupResponseList);
String tabSelected = request.getParameter(Constants.SELECTED_TAB);
if (tabSelected != null)
{
request.setAttribute(Constants.SELECTED_TAB, tabSelected);
}
// For Consent Tracking (Virender Mehta) - End
// get list of Protocol title.
SpecimenCollectionGroupBizLogic bizLogic = (SpecimenCollectionGroupBizLogic) BizLogicFactory.getInstance().getBizLogic(
Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
//populating protocolist bean.
String sourceObjectName = CollectionProtocol.class.getName();
String[] displayNameFields = {"shortTitle"};
String valueField = Constants.SYSTEM_IDENTIFIER;
List list = bizLogic.getList(sourceObjectName, displayNameFields, valueField, true);
request.setAttribute(Constants.PROTOCOL_LIST, list);
Map<Long, String> cpIDTitleMap = Utility.getCPIDTitleMap();
request.setAttribute(Constants.CP_ID_TITLE_MAP, cpIDTitleMap);
//Populating the Site Type bean
sourceObjectName = Site.class.getName();
String[] siteDisplaySiteFields = {"name"};
list = bizLogic.getList(sourceObjectName, siteDisplaySiteFields, valueField, true);
request.setAttribute(Constants.SITELIST, list);
//Populating the participants registered to a given protocol
/**For Migration Start**/
// loadPaticipants(specimenCollectionGroupForm.getCollectionProtocolId() , bizLogic, request);
/**For Migration End**/
//Populating the protocol participants id registered to a given protocol
//By Abhishek Mehta -Performance Enhancement
//loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
String protocolParticipantId = specimenCollectionGroupForm.getProtocolParticipantIdentifier();
//Populating the participants Medical Identifier for a given participant
loadParticipantMedicalIdentifier(specimenCollectionGroupForm.getParticipantId(), bizLogic, request);
//Load Clinical status for a given study calander event point
String changeOn = request.getParameter(Constants.CHANGE_ON);
List calendarEventPointList = null;
if (changeOn != null && changeOn.equals(Constants.COLLECTION_PROTOCOL_ID))
{
calendarEventPointList = new ArrayList();
specimenCollectionGroupForm.setCollectionProtocolEventId(new Long(-1));
}
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(), bizLogic, request, specimenCollectionGroupForm);
calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(), Constants.SYSTEM_IDENTIFIER, new Long(
specimenCollectionGroupForm.getCollectionProtocolEventId()));
// The values of restrict checkbox and the number of specimen must alos populate in edit mode.
if ((isOnChange || operation.equalsIgnoreCase(Constants.EDIT)))
{
// Added by Vijay Pande. Method is created since code was repeating for SUBMITTED_FOR= "AddNew" || "Default" value.
setCalendarEventPoint(calendarEventPointList, request, specimenCollectionGroupForm);
}
// populating clinical Diagnosis field
CDE cde = CDEManager.getCDEManager().getCDE(Constants.CDE_NAME_CLINICAL_DIAGNOSIS);
CDEBizLogic cdeBizLogic = (CDEBizLogic) BizLogicFactory.getInstance().getBizLogic(Constants.CDE_FORM_ID);
List clinicalDiagnosisList = new ArrayList();
clinicalDiagnosisList.add(new NameValueBean(Constants.SELECT_OPTION, "" + Constants.SELECT_OPTION_VALUE));
cdeBizLogic.getFilteredCDE(cde.getPermissibleValues(), clinicalDiagnosisList);
request.setAttribute(Constants.CLINICAL_DIAGNOSIS_LIST, clinicalDiagnosisList);
// populating clinical Status field
// NameValueBean undefinedVal = new NameValueBean(Constants.UNDEFINED,Constants.UNDEFINED);
List clinicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CLINICAL_STATUS, null);
request.setAttribute(Constants.CLINICAL_STATUS_LIST, clinicalStatusList);
//Sets the activityStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.ACTIVITYSTATUSLIST, Constants.ACTIVITY_STATUS_VALUES);
//Sets the collectionStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.COLLECTIONSTATUSLIST, Constants.SCG_COLLECTION_STATUS_VALUES);
Logger.out.debug("CP ID in SCG Action======>" + specimenCollectionGroupForm.getCollectionProtocolId());
Logger.out.debug("Participant ID in SCG Action=====>" + specimenCollectionGroupForm.getParticipantId() + " "
+ specimenCollectionGroupForm.getProtocolParticipantIdentifier());
/**
* Name: Vijay Pande
* check for SUBMITTED_FOR with "AddNew" is added since while coming from specimen->scg->AddNew link for participant-> Register participant -> submit then the SUBMITTED_FOR is equal to "AddNew"
* If the flow is scg->AddNew link for participant-> Register participant -> submit then the SUBMITTED_FOR is equal to "Default"
*/
// -------called from Collection Protocol Registration start-------------------------------
if ((request.getAttribute(Constants.SUBMITTED_FOR) != null)
&& ((request.getAttribute(Constants.SUBMITTED_FOR).equals("Default")) || (request.getAttribute(Constants.SUBMITTED_FOR)
.equals(Constants.ADDNEW_LINK))))
{
Logger.out.debug("Populating CP and Participant in SCG ==== AddNew operation loop");
Long cprId = new Long(specimenCollectionGroupForm.getCollectionProtocolRegistrationId());
if (cprId != null)
{
List collectionProtocolRegistrationList = bizLogic.retrieve(CollectionProtocolRegistration.class.getName(),
Constants.SYSTEM_IDENTIFIER, cprId);
if (!collectionProtocolRegistrationList.isEmpty())
{
Object obj = collectionProtocolRegistrationList.get(0);
CollectionProtocolRegistration cpr = (CollectionProtocolRegistration) obj;
long cpID = cpr.getCollectionProtocol().getId().longValue();
long pID = cpr.getParticipant().getId().longValue();
String ppID = cpr.getProtocolParticipantIdentifier();
Logger.out.debug("cpID : " + cpID + " || pID : " + pID + " || ppID : " + ppID);
specimenCollectionGroupForm.setCollectionProtocolId(cpID);
//Populating the participants registered to a given protocol
/**For Migration Start**/
// loadPaticipants(cpID , bizLogic, request);
/**For Migration Start**/
//By Abhishek Mehta -Performance Enhancement
//loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
/**
* Name: Vijay Pande
* Reviewer Name: Aarti Sharma
* participant associated with collection protocol is explicitly retrived from DB since its lazy load property is true
*/
Participant cprParticipant = (Participant) bizLogic.retrieveAttribute(CollectionProtocolRegistration.class.getName(),
cpr.getId(), Constants.COLUMN_NAME_PARTICIPANT);
// set participant id in request. This is required only in CP based View since SpecimenTreeView.jsp is retrieveing participant id from request
if (cprParticipant.getId() != null)
{
request.setAttribute(Constants.CP_SEARCH_PARTICIPANT_ID, cprParticipant.getId().toString());
}
String firstName = Utility.toString(cprParticipant.getFirstName());
String lastName = Utility.toString(cprParticipant.getLastName());
String birthDate = Utility.toString(cprParticipant.getBirthDate());
String ssn = Utility.toString(cprParticipant.getSocialSecurityNumber());
if (firstName.trim().length() > 0 || lastName.trim().length() > 0 || birthDate.trim().length() > 0 || ssn.trim().length() > 0)
{
specimenCollectionGroupForm.setParticipantId(pID);
specimenCollectionGroupForm.setRadioButtonForParticipant(1);
specimenCollectionGroupForm.setParticipantName(lastName + ", " + firstName);
}
//Populating the protocol participants id registered to a given protocol
else if (cpr.getProtocolParticipantIdentifier() != null)
{
specimenCollectionGroupForm.setProtocolParticipantIdentifier(ppID);
specimenCollectionGroupForm.setRadioButtonForParticipant(2);
}
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(), bizLogic, request, specimenCollectionGroupForm);
//Load Clinical status for a given study calander event point
calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(), Constants.SYSTEM_IDENTIFIER, new Long(
specimenCollectionGroupForm.getCollectionProtocolEventId()));
if (isOnChange && !calendarEventPointList.isEmpty())
{
setCalendarEventPoint(calendarEventPointList, request, specimenCollectionGroupForm);
}
}
}
request.setAttribute(Constants.SUBMITTED_FOR, "Default");
}
//************* ForwardTo implementation *************
HashMap forwardToHashMap = (HashMap) request.getAttribute("forwardToHashMap");
if (forwardToHashMap != null)
{
/**
* Name: Falguni Sachde
* Reviewer Name:
* Attribute collectionProtocolName added to show Collection ProtocolName in Add mode only.
*/
Long collectionProtocolId = (Long) forwardToHashMap.get("collectionProtocolId");
String collectionProtocolName = (String) request.getSession().getAttribute("cpTitle");
if (collectionProtocolId == null && request.getParameter("cpId") != null && !request.getParameter("cpId").equals("null"))
{
collectionProtocolId = new Long(request.getParameter("cpId"));
}
Long participantId = (Long) forwardToHashMap.get("participantId");
String participantProtocolId = (String) forwardToHashMap.get("participantProtocolId");
specimenCollectionGroupForm.setCollectionProtocolId(collectionProtocolId.longValue());
specimenCollectionGroupForm.setCollectionProtocolName(collectionProtocolName);
/**
* Name : Deepti Shelar
* Bug id : 4216
* Patch id : 4216_1
* Description : populating list of ParticipantMedicalIdentifiers for given participant id
*/
loadParticipantMedicalIdentifier(participantId, bizLogic, request);
if (participantId != null && participantId.longValue() != 0)
{
//Populating the participants registered to a given protocol
/**For Migration Start**/
// loadPaticipants(collectionProtocolId.longValue(), bizLogic, request);
/**For Migration End**/
//By Abhishek Mehta -Performance Enhancement
//loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
specimenCollectionGroupForm.setParticipantId(participantId.longValue());
specimenCollectionGroupForm.setRadioButtonForParticipant(1);
request.setAttribute(Constants.CP_SEARCH_PARTICIPANT_ID, participantId.toString());
/**For Migration Start**/
List participantList = bizLogic.retrieve(Participant.class.getName(), Constants.SYSTEM_IDENTIFIER, Utility.toString(participantId));
if (participantList != null)
{
Participant participant = (Participant) participantList.get(0);
String firstName = "";
String lastName = "";
if (participant.getFirstName() != null)
{
firstName = participant.getFirstName();
}
if (participant.getLastName() != null)
{
lastName = participant.getLastName();
}
if (!firstName.equals("") && !lastName.equals(""))
{
specimenCollectionGroupForm.setParticipantName(lastName + ", " + firstName);
}
else if (lastName.equals("") && !firstName.equals(""))
{
specimenCollectionGroupForm.setParticipantName(participant.getFirstName());
}
else if (firstName.equals("") && !lastName.equals(""))
{
specimenCollectionGroupForm.setParticipantName(participant.getLastName());
}
}
/**For Migration End**/
/**
* Name : Deepti Shelar
* Reviewer Name : Sachin Lale
* Bug id : FutureSCG
* Patch Id : FutureSCG_1
* Description : setting participantProtocolId to form
*/
if (participantProtocolId == null)
{
participantProtocolId = getParticipantProtocolIdForCPAndParticipantId(participantId.toString(), collectionProtocolId.toString(),
bizLogic);
if (participantProtocolId != null)
{
specimenCollectionGroupForm.setProtocolParticipantIdentifier(participantProtocolId);
specimenCollectionGroupForm.setRadioButtonForParticipant(2);
}
}
}
else if (participantProtocolId != null)
{
//Populating the participants registered to a given protocol
/**For Migration Start**/
// loadPaticipants(collectionProtocolId.longValue(), bizLogic, request);
/**For Migration End**/
//By Abhishek Mehta -Performance Enhancement
//loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
specimenCollectionGroupForm.setProtocolParticipantIdentifier(participantProtocolId);
specimenCollectionGroupForm.setRadioButtonForParticipant(2);
String cpParticipantId = getParticipantIdForProtocolId(participantProtocolId, bizLogic);
if (cpParticipantId != null)
{
request.setAttribute(Constants.CP_SEARCH_PARTICIPANT_ID, cpParticipantId);
}
}
/**
* Patch Id : FutureSCG_3
* Description : Setting number of specimens and restricted checkbox
*/
/**
* Removing the above patch, as it no more required. Now the new CP based entry page takes care of this.
*/
Long cpeId = (Long) forwardToHashMap.get("COLLECTION_PROTOCOL_EVENT_ID");
if (cpeId != null)
{
specimenCollectionGroupForm.setCollectionProtocolEventId(cpeId);
/*List cpeList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(),Constants.SYSTEM_IDENTIFIER,cpeId);
if(!cpeList.isEmpty())
{
setNumberOfSpecimens(request, specimenCollectionGroupForm, cpeList);
}*/
}
//Bug 1915:SpecimenCollectionGroup.Study Calendar Event Point not populated when page is loaded through proceedTo
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(), bizLogic, request, specimenCollectionGroupForm);
//Load Clinical status for a given study calander event point
calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(), Constants.SYSTEM_IDENTIFIER, new Long(
specimenCollectionGroupForm.getCollectionProtocolEventId()));
if (!calendarEventPointList.isEmpty())
{
setCalendarEventPoint(calendarEventPointList, request, specimenCollectionGroupForm);
}
Logger.out.debug("CollectionProtocolID found in forwardToHashMap========>>>>>>" + collectionProtocolId);
Logger.out.debug("ParticipantID found in forwardToHashMap========>>>>>>" + participantId);
Logger.out.debug("ParticipantProtocolID found in forwardToHashMap========>>>>>>" + participantProtocolId);
}
//************* ForwardTo implementation *************
//Populate the group name field with default value in the form of
//<Collection Protocol Name>_<Participant ID>_<Group Id>
int groupNumber = bizLogic.getNextGroupNumber();
//Get the collection protocol title for the collection protocol Id selected
String collectionProtocolTitle = "";
String collectionProtocolName = "";
list = bizLogic.retrieve(CollectionProtocol.class.getName(), valueField, new Long(specimenCollectionGroupForm.getCollectionProtocolId()));
if (!list.isEmpty())
{
CollectionProtocol collectionProtocol = (CollectionProtocol) list.get(0);
collectionProtocolTitle = collectionProtocol.getTitle();
collectionProtocolName = (String) collectionProtocol.getShortTitle();
specimenCollectionGroupForm.setCollectionProtocolName(collectionProtocolName);
}
long groupParticipantId = specimenCollectionGroupForm.getParticipantId();
//check if the reset name link was clicked
String resetName = request.getParameter(Constants.RESET_NAME);
//Set the name to default if reset name link was clicked or page is loading for first time
//through add link or forward to link
if (forwardToHashMap != null || (specimenCollectionGroupForm.getName() != null && specimenCollectionGroupForm.getName().equals(""))
|| (resetName != null && resetName.equals("Yes")))
{
if (!collectionProtocolTitle.equals("")
&& (groupParticipantId > 0 || (protocolParticipantId != null && !protocolParticipantId.equals(""))))
{
//Poornima:Bug 2833 - Error thrown when adding a specimen collection group
//Max length of CP is 150 and Max length of SCG is 55, in Oracle the name does not truncate
//and it is giving error. So the title is truncated in case it is longer than 30 .
String maxCollTitle = collectionProtocolName;
if (collectionProtocolName.length() > Constants.COLLECTION_PROTOCOL_TITLE_LENGTH)
{
maxCollTitle = collectionProtocolName.substring(0, Constants.COLLECTION_PROTOCOL_TITLE_LENGTH - 1);
}
//During add operation the id to set in the default name is generated
if (operation.equals(Constants.ADD))
{
specimenCollectionGroupForm.setName(maxCollTitle + "_" + groupParticipantId + "_" + groupNumber);
}
//During edit operation the id to set in the default name using the id
else if (operation.equals(Constants.EDIT) && (resetName != null && resetName.equals("Yes")))
{
if (groupParticipantId > 0)
{
specimenCollectionGroupForm.setName(maxCollTitle + "_" + groupParticipantId + "_" + specimenCollectionGroupForm.getId());
}
else
{
specimenCollectionGroupForm.setName(maxCollTitle + "_" + protocolParticipantId + "_" + specimenCollectionGroupForm.getId());
}
}
}
}
request.setAttribute(Constants.PAGEOF, pageOf);
Logger.out.debug("page of in Specimen coll grp action:" + request.getParameter(Constants.PAGEOF));
// -------called from Collection Protocol Registration end -------------------------------
//Falguni:Performance Enhancement.
Long scgEntityId = null;
if (CatissueCoreCacheManager.getInstance().getObjectFromCache("scgEntityId") != null)
{
scgEntityId = (Long) CatissueCoreCacheManager.getInstance().getObjectFromCache("scgEntityId");
}
else
{
scgEntityId = AnnotationUtil.getEntityId(AnnotationConstants.ENTITY_NAME_SPECIMEN_COLLN_GROUP);
CatissueCoreCacheManager.getInstance().addObjectToCache("scgEntityId", scgEntityId);
}
request.setAttribute("scgEntityId", scgEntityId);
/**
* Name : Ashish Gupta
* Reviewer Name : Sachin Lale
* Bug ID: 2741
* Patch ID: 2741_11
* Description: Methods to set default events on SCG page
*/
setDefaultEvents(request, specimenCollectionGroupForm, operation);
request.setAttribute("scgForm", specimenCollectionGroupForm);
/* Bug ID: 4135
* Patch ID: 4135_2
* Description: Setting the ids in collection and received events associated with this scg
*/
//When opening in Edit mode, to set the ids of collection event parameters and received event parameters
if (specimenCollectionGroupForm.getId() != 0)
{
setEventsId(specimenCollectionGroupForm, bizLogic);
}
// set associated identified report id
Long reportId = getAssociatedIdentifiedReportId(specimenCollectionGroupForm.getId());
if (reportId == null)
{
reportId = new Long(-1);
}
else if (Utility.isQuarantined(reportId))
{
reportId = new Long(-2);
}
HttpSession session = request.getSession();
session.setAttribute(Constants.IDENTIFIED_REPORT_ID, reportId);
return mapping.findForward(pageOf);
}
/**
* @param specimenCollectionGroupForm
* @param bizLogic
* @throws DAOException
*/
private void setEventsId(SpecimenCollectionGroupForm specimenCollectionGroupForm, SpecimenCollectionGroupBizLogic bizLogic) throws DAOException
{
String scgId = "" + specimenCollectionGroupForm.getId();
List scglist = bizLogic.retrieve(SpecimenCollectionGroup.class.getName(), "id", scgId);
if (scglist != null && !scglist.isEmpty())
{
SpecimenCollectionGroup scg = (SpecimenCollectionGroup) scglist.get(0);
Collection eventsColl = scg.getSpecimenEventParametersCollection();
CollectionEventParameters collectionEventParameters = null;
ReceivedEventParameters receivedEventParameters = null;
if (eventsColl != null && !eventsColl.isEmpty())
{
Iterator iter = eventsColl.iterator();
while (iter.hasNext())
{
Object temp = iter.next();
if (temp instanceof CollectionEventParameters)
{
collectionEventParameters = (CollectionEventParameters) temp;
}
else if (temp instanceof ReceivedEventParameters)
{
receivedEventParameters = (ReceivedEventParameters) temp;
}
}
// Setting the ids
specimenCollectionGroupForm.setCollectionEventId(collectionEventParameters.getId().longValue());
specimenCollectionGroupForm.setReceivedEventId(receivedEventParameters.getId().longValue());
}
}
}
/**
* @param request
* @param specimenCollectionGroupForm
*/
private void setDefaultEvents(HttpServletRequest request, SpecimenCollectionGroupForm specimenCollectionGroupForm, String operation)
throws DAOException
{
setDateParameters(specimenCollectionGroupForm, request);
if (specimenCollectionGroupForm.getCollectionEventCollectionProcedure() == null)
{
specimenCollectionGroupForm.setCollectionEventCollectionProcedure((String) DefaultValueManager
.getDefaultValue(Constants.DEFAULT_COLLECTION_PROCEDURE));
}
if (specimenCollectionGroupForm.getCollectionEventContainer() == null)
{
specimenCollectionGroupForm.setCollectionEventContainer((String) DefaultValueManager.getDefaultValue(Constants.DEFAULT_CONTAINER));
}
if (specimenCollectionGroupForm.getReceivedEventReceivedQuality() == null)
{
specimenCollectionGroupForm.setReceivedEventReceivedQuality((String) DefaultValueManager
.getDefaultValue(Constants.DEFAULT_RECEIVED_QUALITY));
}
//setting the collector and receiver drop downs
setUserInForm(request, operation, specimenCollectionGroupForm);
//Setting the List for drop downs
setEventsListInRequest(request);
}
/**
* @param request
*/
private void setEventsListInRequest(HttpServletRequest request)
{
//setting the procedure
List procedureList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COLLECTION_PROCEDURE, null);
request.setAttribute(Constants.PROCEDURE_LIST, procedureList);
// set the container lists
List containerList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CONTAINER, null);
request.setAttribute(Constants.CONTAINER_LIST, containerList);
//setting the quality for received events
List qualityList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_RECEIVED_QUALITY, null);
request.setAttribute(Constants.RECEIVED_QUALITY_LIST, qualityList);
// Sets the hourList attribute to be used in the Add/Edit FrozenEventParameters Page.
request.setAttribute(Constants.HOUR_LIST, Constants.HOUR_ARRAY);
//Sets the minutesList attribute to be used in the Add/Edit FrozenEventParameters Page.
request.setAttribute(Constants.MINUTES_LIST, Constants.MINUTES_ARRAY);
}
/**
* @param request
* @param operation
* @param specimenCollectionGroupForm
* @throws DAOException
*/
private void setUserInForm(HttpServletRequest request, String operation, SpecimenCollectionGroupForm specimenCollectionGroupForm)
throws DAOException
{
UserBizLogic userBizLogic = (UserBizLogic) BizLogicFactory.getInstance().getBizLogic(Constants.USER_FORM_ID);
Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
SessionDataBean sessionData = getSessionData(request);
if (sessionData != null)
{
String user = sessionData.getLastName() + ", " + sessionData.getFirstName();
long collectionEventUserId = EventsUtil.getIdFromCollection(userCollection, user);
if (specimenCollectionGroupForm.getCollectionEventUserId() == 0)
{
specimenCollectionGroupForm.setCollectionEventUserId(collectionEventUserId);
}
if (specimenCollectionGroupForm.getReceivedEventUserId() == 0)
{
specimenCollectionGroupForm.setReceivedEventUserId(collectionEventUserId);
}
}
}
/**
* @param specimenForm
*/
private void setDateParameters(SpecimenCollectionGroupForm specimenForm, HttpServletRequest request)
{
// set the current Date and Time for the event.
Calendar cal = Calendar.getInstance();
//Collection Event fields
if (specimenForm.getCollectionEventdateOfEvent() == null)
{
specimenForm.setCollectionEventdateOfEvent(Utility.parseDateToString(cal.getTime(), Constants.DATE_PATTERN_MM_DD_YYYY));
}
if (specimenForm.getCollectionEventTimeInHours() == null)
{
specimenForm.setCollectionEventTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (specimenForm.getCollectionEventTimeInMinutes() == null)
{
specimenForm.setCollectionEventTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
//ReceivedEvent Fields
if (specimenForm.getReceivedEventDateOfEvent() == null)
{
specimenForm.setReceivedEventDateOfEvent(Utility.parseDateToString(cal.getTime(), Constants.DATE_PATTERN_MM_DD_YYYY));
}
if (specimenForm.getReceivedEventTimeInHours() == null)
{
specimenForm.setReceivedEventTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (specimenForm.getReceivedEventTimeInMinutes() == null)
{
specimenForm.setReceivedEventTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
/**For Migration Start**/
/* private void loadPaticipants(long protocolID, IBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String [] displayParticipantFields = {"participant.id"};
String valueField = "participant."+Constants.SYSTEM_IDENTIFIER;
String whereColumnName[] = {"collectionProtocol."+Constants.SYSTEM_IDENTIFIER,"participant.id"};
String whereColumnCondition[];
Object[] whereColumnValue;
if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
{
whereColumnCondition = new String[]{"=","is not"};
whereColumnValue=new Object[]{new Long(protocolID),null};
}
else
{
// for ORACLE
whereColumnCondition = new String[]{"=",Constants.IS_NOT_NULL};
whereColumnValue=new Object[]{new Long(protocolID),""};
}
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = ", ";
List list = bizLogic.getList(sourceObjectName, displayParticipantFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, true);
//get list of Participant's names
valueField = Constants.SYSTEM_IDENTIFIER;
sourceObjectName = Participant.class.getName();
String[] participantsFields = {"lastName","firstName","birthDate","socialSecurityNumber"};
String[] whereColumnName2 = {"lastName","firstName","birthDate","socialSecurityNumber"};
String[] whereColumnCondition2 = {"!=","!=","is not","is not"};
Object[] whereColumnValue2 = {"","",null,null};
if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
{
whereColumnCondition2 = new String[]{"!=","!=","is not","is not"};
whereColumnValue2=new String[]{"","",null,null};
}
else
{
// for ORACLE
whereColumnCondition2 = new String[]{Constants.IS_NOT_NULL,Constants.IS_NOT_NULL,Constants.IS_NOT_NULL,Constants.IS_NOT_NULL};
whereColumnValue2=new String[]{"","","",""};
}
String joinCondition2 = Constants.OR_JOIN_CONDITION;
String separatorBetweenFields2 = ", ";
List listOfParticipants = bizLogic.getList(sourceObjectName, participantsFields, valueField, whereColumnName2,
whereColumnCondition2, whereColumnValue2, joinCondition2, separatorBetweenFields, false);
// removing blank participants from the list of Participants
list=removeBlankParticipant(list, listOfParticipants);
//Mandar bug id:1628 :- sort participant dropdown list
Collections.sort(list );
Logger.out.debug("Paticipants List"+list);
request.setAttribute(Constants.PARTICIPANT_LIST, list);
}
private List removeBlankParticipant(List list, List listOfParticipants)
{
List listOfActiveParticipant=new ArrayList();
for(int i=0; i<list.size(); i++)
{
NameValueBean nameValueBean =(NameValueBean)list.get(i);
if(Long.parseLong(nameValueBean.getValue()) == -1)
{
listOfActiveParticipant.add(list.get(i));
continue;
}
for(int j=0; j<listOfParticipants.size(); j++)
{
if(Long.parseLong(((NameValueBean)listOfParticipants.get(j)).getValue()) == -1)
continue;
NameValueBean participantsBean = (NameValueBean)listOfParticipants.get(j);
if( nameValueBean.getValue().equals(participantsBean.getValue()) )
{
listOfActiveParticipant.add(listOfParticipants.get(j));
break;
}
}
}
Logger.out.debug("No.Of Active Participants Registered with Protocol~~~~~~~~~~~~~~~~~~~~~~~>"+listOfActiveParticipant.size());
return listOfActiveParticipant;
}
*/
/**Commented by Abhishek Mehta
* Method to load protocol participant identifier number list
* @param protocolID
* @param bizLogic
* @param request
* @throws Exception
*/
/*private void loadPaticipantNumberList(long protocolID, IBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String displayParticipantNumberFields[] = {"protocolParticipantIdentifier"};
String valueField = "protocolParticipantIdentifier";
String whereColumnName[] = {"collectionProtocol."+Constants.SYSTEM_IDENTIFIER, "protocolParticipantIdentifier"};
String whereColumnCondition[];// = {"=","!="};
Object[] whereColumnValue;// = {new Long(protocolID),"null"};
// if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
// {
whereColumnCondition = new String[]{"=","!="};
whereColumnValue = new Object[]{new Long(protocolID),"null"};
// }
// else
// {
// whereColumnCondition = new String[]{"=","!=null"};
// whereColumnValue = new Object[]{new Long(protocolID),""};
// }
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayParticipantNumberFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, true);
Logger.out.debug("Paticipant Number List"+list);
request.setAttribute(Constants.PROTOCOL_PARTICIPANT_NUMBER_LIST, list);
}*/
/**
* Method to load list of collection protocol event point
* @param protocolID
* @param bizLogic
* @param request
* @param form
* @throws Exception
*/
private void loadCollectionProtocolEvent(long protocolID, IBizLogic bizLogic, HttpServletRequest request, SpecimenCollectionGroupForm form)
throws Exception
{
String sourceObjectName = CollectionProtocolEvent.class.getName();
String displayEventFields[] = {"studyCalendarEventPoint", "collectionPointLabel"};
String valueField = "id";
String whereColumnName[] = {"collectionProtocol." + Constants.SYSTEM_IDENTIFIER};
String whereColumnCondition[] = {"="};
Object[] whereColumnValue = {new Long(protocolID)};
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = ",";
List list = bizLogic.getList(sourceObjectName, displayEventFields, valueField, whereColumnName, whereColumnCondition, whereColumnValue,
joinCondition, separatorBetweenFields, false);
request.setAttribute(Constants.STUDY_CALENDAR_EVENT_POINT_LIST, list);
if (list.size() > 1 && form.getCollectionProtocolEventId() <= 0)
{
form.setCollectionProtocolEventId(new Long(((NameValueBean) list.get(1)).getValue()));
}
}
/**
* Method to load list of participant medical identifier
* @param participantID
* @param bizLogic
* @param request
* @throws Exception
*/
private void loadParticipantMedicalIdentifier(long participantID, IBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = ParticipantMedicalIdentifier.class.getName();
String displayEventFields[] = {"medicalRecordNumber"};
String valueField = Constants.SYSTEM_IDENTIFIER;
String whereColumnName[] = {"participant." + Constants.SYSTEM_IDENTIFIER, "medicalRecordNumber"};
String whereColumnCondition[] = {"=", "!="};
Object[] whereColumnValue = {new Long(participantID), "null"};
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayEventFields, valueField, whereColumnName, whereColumnCondition, whereColumnValue,
joinCondition, separatorBetweenFields, false);
request.setAttribute(Constants.PARTICIPANT_MEDICAL_IDNETIFIER_LIST, list);
}
/**
* Method to retrieve participant id from the protocol participant id
* @param participantProtocolId
* @param bizLogic
* @return
* @throws Exception
*/
private String getParticipantIdForProtocolId(String participantProtocolId, IBizLogic bizLogic) throws Exception
{
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String selectColumnName[] = {"participant.id"};
String whereColumnName[] = {"protocolParticipantIdentifier"};
String whereColumnCondition[] = {"="};
Object[] whereColumnValue = {participantProtocolId};
List participantList = bizLogic.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue,
Constants.AND_JOIN_CONDITION);
if (participantList != null && !participantList.isEmpty())
{
String participantId = ((Long) participantList.get(0)).toString();
return participantId;
}
return null;
}
/**
* Method to retrieve participant protocol identifier for given CP and participant id
* @param participantId
* @param cpId
* @param bizLogic
* @return
* @throws Exception
*/
private String getParticipantProtocolIdForCPAndParticipantId(String participantId, String cpId, IBizLogic bizLogic) throws Exception
{
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String selectColumnName[] = {"protocolParticipantIdentifier"};
String whereColumnName[] = {"participant.id", "collectionProtocol.id"};
String whereColumnCondition[] = {"=", "="};
Object[] whereColumnValue = {participantId, cpId};
List list = bizLogic.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue,
Constants.AND_JOIN_CONDITION);
if (list != null && !list.isEmpty())
{
Iterator iter = list.iterator();
while (iter.hasNext())
{
Object id = (Object) iter.next();
if (id != null)
{
return id.toString();
}
}
}
return null;
}
/**
* Method to set default values related to calendar event point list
* @param calendarEventPointList calendar event point list
* @param request object of HttpServletRequest
* @param specimenCollectionGroupForm object of specimenCollectionGroup action form
* @throws DAOException
*/
private void setCalendarEventPoint(List calendarEventPointList, HttpServletRequest request,
SpecimenCollectionGroupForm specimenCollectionGroupForm) throws DAOException
{
// Patch ID: Bug#3184_27
//By Abhishek Mehta
int numberOfSpecimen = 1;
if (!calendarEventPointList.isEmpty())
{
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent) calendarEventPointList.get(0);
//Set checkbox status depending upon the days of study calendar event point. If it is zero, then unset the restrict
//checkbox, otherwise set the restrict checkbox
Double studyCalendarEventPoint = collectionProtocolEvent.getStudyCalendarEventPoint();
if (studyCalendarEventPoint.doubleValue() == 0)
{
specimenCollectionGroupForm.setRestrictSCGCheckbox("false");
}
else
{
specimenCollectionGroupForm.setRestrictSCGCheckbox("true");
}
}
else if (calendarEventPointList.isEmpty())
{
//Set checkbox status
specimenCollectionGroupForm.setRestrictSCGCheckbox("false");
}
//Sets the value for number of specimen field on the specimen collection group page.
//Set the number of actual specimen requirements for validation purpose.
//This value is used in validate method of SpecimenCollectionGroupForm.java.
// request.setAttribute(Constants.NUMBER_OF_SPECIMEN_REQUIREMENTS, numberOfSpecimen + "");
}
//Consent Tracking Virender Mehta
/**
* @param idOfSelectedRadioButton Id for selected radio button.
* @param cp_id CollectionProtocolID CollectionProtocolID selected by dropdown
* @param indexType i.e Which Radio button is selected participantId or protocolParticipantIdentifier
* @return collectionProtocolRegistration CollectionProtocolRegistration object
*/
private CollectionProtocolRegistration getcollectionProtocolRegistrationObj(String idOfSelectedRadioButton, String cp_id, String indexType)
throws DAOException
{
CollectionProtocolRegistrationBizLogic collectionProtocolRegistrationBizLogic = (CollectionProtocolRegistrationBizLogic) BizLogicFactory
.getInstance().getBizLogic(Constants.COLLECTION_PROTOCOL_REGISTRATION_FORM_ID);
String[] colName = new String[2];
if (indexType.equalsIgnoreCase(Constants.PARTICIPANT_ID))
{
colName[0] = "participant.id";
colName[1] = "collectionProtocol.id";
}
else
{
colName[0] = "protocolParticipantIdentifier";
colName[1] = "collectionProtocol.id";
}
String[] colCondition = {"=", "="};
String[] val = new String[2];
val[0] = idOfSelectedRadioButton;
val[1] = cp_id;
List collProtRegObj = collectionProtocolRegistrationBizLogic.retrieve(CollectionProtocolRegistration.class.getName(), colName, colCondition,
val, null);
CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration) collProtRegObj.get(0);
return collectionProtocolRegistration;
}
/**
* For ConsentTracking Preparing consentResponseForScgValues for populating Dynamic contents on the UI
* @param partiResponseCollection This Containes the collection of ConsentTier Response at CPR level
* @param statusResponseCollection This Containes the collection of ConsentTier Response at Specimen level
* @return tempMap
*/
private Map prepareSCGResponseMap(Collection statusResponseCollection, Collection partiResponseCollection)
{
Map tempMap = new HashMap();
Long consentTierID;
Long consentID;
if (partiResponseCollection != null || statusResponseCollection != null)
{
int i = 0;
Iterator statusResponsIter = statusResponseCollection.iterator();
while (statusResponsIter.hasNext())
{
ConsentTierStatus consentTierstatus = (ConsentTierStatus) statusResponsIter.next();
consentTierID = consentTierstatus.getConsentTier().getId();
Iterator participantResponseIter = partiResponseCollection.iterator();
while (participantResponseIter.hasNext())
{
ConsentTierResponse consentTierResponse = (ConsentTierResponse) participantResponseIter.next();
consentID = consentTierResponse.getConsentTier().getId();
if (consentTierID.longValue() == consentID.longValue())
{
ConsentTier consent = consentTierResponse.getConsentTier();
String idKey = "ConsentBean:" + i + "_consentTierID";
String statementKey = "ConsentBean:" + i + "_statement";
String participantResponsekey = "ConsentBean:" + i + "_participantResponse";
String participantResponceIdKey = "ConsentBean:" + i + "_participantResponseID";
String scgResponsekey = "ConsentBean:" + i + "_specimenCollectionGroupLevelResponse";
String scgResponseIDkey = "ConsentBean:" + i + "_specimenCollectionGroupLevelResponseID";
tempMap.put(idKey, consent.getId());
tempMap.put(statementKey, consent.getStatement());
tempMap.put(participantResponsekey, consentTierResponse.getResponse());
tempMap.put(participantResponceIdKey, consentTierResponse.getId());
tempMap.put(scgResponsekey, consentTierstatus.getStatus());
tempMap.put(scgResponseIDkey, consentTierstatus.getId());
i++;
break;
}
}
}
return tempMap;
}
else
{
return null;
}
}
/**
* Prepare Map for Consent tiers
* @param participantResponseList This list will be iterated to map to populate participant Response status.
* @return tempMap
*/
private Map prepareConsentMap(List participantResponseList)
{
Map tempMap = new HashMap();
if (participantResponseList != null)
{
int i = 0;
Iterator consentResponseCollectionIter = participantResponseList.iterator();
while (consentResponseCollectionIter.hasNext())
{
ConsentTierResponse consentTierResponse = (ConsentTierResponse) consentResponseCollectionIter.next();
ConsentTier consent = consentTierResponse.getConsentTier();
String idKey = "ConsentBean:" + i + "_consentTierID";
String statementKey = "ConsentBean:" + i + "_statement";
String responseKey = "ConsentBean:" + i + "_participantResponse";
String participantResponceIdKey = "ConsentBean:" + i + "_participantResponseID";
String scgResponsekey = "ConsentBean:" + i + "_specimenCollectionGroupLevelResponse";
String scgResponseIDkey = "ConsentBean:" + i + "_specimenCollectionGroupLevelResponseID";
tempMap.put(idKey, consent.getId());
tempMap.put(statementKey, consent.getStatement());
tempMap.put(responseKey, consentTierResponse.getResponse());
tempMap.put(participantResponceIdKey, consentTierResponse.getId());
tempMap.put(scgResponsekey, consentTierResponse.getResponse());
tempMap.put(scgResponseIDkey, null);
i++;
}
}
return tempMap;
}
/**
* This function will return CollectionProtocolRegistration object
* @param scg_id Selected SpecimenCollectionGroup ID
* @return collectionProtocolRegistration
*/
private SpecimenCollectionGroup getSCGObj(String scg_id) throws DAOException
{
SpecimenCollectionGroupBizLogic specimenCollectionBizLogic = (SpecimenCollectionGroupBizLogic) BizLogicFactory.getInstance().getBizLogic(
Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
String colName = "id";
List getSCGIdFromDB = specimenCollectionBizLogic.retrieve(SpecimenCollectionGroup.class.getName(), colName, scg_id);
SpecimenCollectionGroup specimenCollectionGroupObject = (SpecimenCollectionGroup) getSCGIdFromDB.get(0);
return specimenCollectionGroupObject;
}
//Consent Tracking Virender Mehta
/**
* This function is used for retriving specimen from Specimen collection group Object
* @param specimenObj
* @param finalDataList
* @throws DAOException
*/
private void getSpecimenDetails(SpecimenCollectionGroup specimenCollectionGroupObj, List finalDataList) throws DAOException
{
IBizLogic bizLogic = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC);
Collection specimen = null;
if (specimenCollectionGroupObj.getId() != null)
{
specimen = (Collection) bizLogic.retrieveAttribute(SpecimenCollectionGroup.class.getName(), specimenCollectionGroupObj.getId(),
"elements(specimenCollection)");
}
//Collection specimen = specimenCollectionGroupObj.getSpecimenCollection();
Iterator specimenIterator = specimen.iterator();
while (specimenIterator.hasNext())
{
Specimen specimenObj = (Specimen) specimenIterator.next();
getDetailsOfSpecimen(specimenObj, finalDataList);
}
}
/**
* This function is used for retriving specimen and sub specimen's attributes.
* @param specimenObj
* @param finalDataList
* @throws DAOException
*/
private void getDetailsOfSpecimen(Specimen specimenObj, List finalDataList) throws DAOException
{
IBizLogic bizLogic = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC);
List specimenDetailList = new ArrayList();
if (specimenObj.getActivityStatus().equals(Constants.ACTIVITY_STATUS_ACTIVE))
{
specimenDetailList.add(specimenObj.getLabel());
specimenDetailList.add(specimenObj.getType());
if (specimenObj.getStorageContainer() == null)
{
specimenDetailList.add(Constants.VIRTUALLY_LOCATED);
}
else
{
StorageContainer storageContainer = (StorageContainer) bizLogic.retrieveAttribute(Specimen.class.getName(), specimenObj.getId(),
"storageContainer");
//specimenObj.getStorageContainer().getName()+": X-Axis-"+specimenObj.getPositionDimensionOne()+", Y-Axis-"+specimenObj.getPositionDimensionTwo();
String storageLocation = storageContainer.getName() + ": X-Axis-" + specimenObj.getPositionDimensionOne() + ", Y-Axis-"
+ specimenObj.getPositionDimensionTwo();
specimenDetailList.add(storageLocation);
}
specimenDetailList.add(specimenObj.getClassName());
finalDataList.add(specimenDetailList);
}
}
/**
* This function adds the columns to the List
* @return columnList
*/
public List columnNames()
{
List columnList = new ArrayList();
columnList.add(Constants.LABLE);
columnList.add(Constants.TYPE);
columnList.add(Constants.STORAGE_CONTAINER_LOCATION);
columnList.add(Constants.CLASS_NAME);
return columnList;
}
private Long getAssociatedIdentifiedReportId(Long scgId) throws DAOException
{
IdentifiedSurgicalPathologyReportBizLogic bizLogic = (IdentifiedSurgicalPathologyReportBizLogic) BizLogicFactory.getInstance().getBizLogic(
IdentifiedSurgicalPathologyReport.class.getName());
String sourceObjectName = IdentifiedSurgicalPathologyReport.class.getName();
String displayEventFields[] = {"id"};
String valueField = Constants.SYSTEM_IDENTIFIER;
String whereColumnName[] = {Constants.COLUMN_NAME_SCG_ID};
String whereColumnCondition[] = {"="};
Object[] whereColumnValue = {scgId};
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayEventFields, valueField, whereColumnName, whereColumnCondition, whereColumnValue,
joinCondition, separatorBetweenFields, false);
if (list != null && list.size() > 1)
{
NameValueBean nvBean = (NameValueBean) list.get(1);
return (new Long(nvBean.getValue()));
}
return null;
}
}
| WEB-INF/src/edu/wustl/catissuecore/action/SpecimenCollectionGroupAction.java | /**
* <p>Title: SpecimenCollectionGroupAction Class>
* <p>Description: SpecimenCollectionGroupAction initializes the fields in the
* New Specimen Collection Group page.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Ajay Sharma
* @version 1.00
*/
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.action.annotations.AnnotationConstants;
import edu.wustl.catissuecore.actionForm.SpecimenCollectionGroupForm;
import edu.wustl.catissuecore.bizlogic.AnnotationUtil;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.CollectionProtocolRegistrationBizLogic;
import edu.wustl.catissuecore.bizlogic.IdentifiedSurgicalPathologyReportBizLogic;
import edu.wustl.catissuecore.bizlogic.SpecimenCollectionGroupBizLogic;
import edu.wustl.catissuecore.bizlogic.UserBizLogic;
import edu.wustl.catissuecore.domain.CollectionEventParameters;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolEvent;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.ConsentTier;
import edu.wustl.catissuecore.domain.ConsentTierResponse;
import edu.wustl.catissuecore.domain.ConsentTierStatus;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.domain.ParticipantMedicalIdentifier;
import edu.wustl.catissuecore.domain.ReceivedEventParameters;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.SpecimenCollectionRequirementGroup;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.domain.pathology.IdentifiedSurgicalPathologyReport;
import edu.wustl.catissuecore.util.CatissueCoreCacheManager;
import edu.wustl.catissuecore.util.EventsUtil;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.DefaultValueManager;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.common.action.SecureAction;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.CDEBizLogic;
import edu.wustl.common.bizlogic.IBizLogic;
import edu.wustl.common.cde.CDE;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.logger.Logger;
/**
* SpecimenCollectionGroupAction initializes the fields in the
* New Specimen Collection Group page.
* @author ajay_sharma
*/
public class SpecimenCollectionGroupAction extends SecureAction
{
/**
* Overrides the execute method of Action class.
* @param mapping object of ActionMapping
* @param form object of ActionForm
* @param request object of HttpServletRequest
* @param response object of HttpServletResponse
* @throws Exception generic exception
*/
public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
//changes made by Baljeet
String treeRefresh = request.getParameter("refresh");
request.setAttribute("refresh", treeRefresh);
SpecimenCollectionGroupForm specimenCollectionGroupForm = (SpecimenCollectionGroupForm) form;
IBizLogic bizLogicObj = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC);
Logger.out.debug("SCGA : " + specimenCollectionGroupForm.getId());
String nodeId = null;
/**
* Bug id : 4213
* Patch id : 4213_2
* Description : getting parameters from request and keeping them in seesion to keep the node in tree selected.
*/
if (request.getParameter("clickedNodeId") != null)
{
nodeId = request.getParameter("clickedNodeId");
request.getSession().setAttribute("nodeId", nodeId);
}
// set the menu selection
request.setAttribute(Constants.MENU_SELECTED, "14");
//pageOf and operation attributes required for Advance Query Object view.
String pageOf = request.getParameter(Constants.PAGEOF);
//Gets the value of the operation parameter.
String operation = (String) request.getParameter(Constants.OPERATION);
//Sets the operation attribute to be used in the Edit/View Specimen Collection Group Page in Advance Search Object View.
request.setAttribute(Constants.OPERATION, operation);
if (operation.equalsIgnoreCase(Constants.ADD))
{
specimenCollectionGroupForm.setId(0);
Logger.out.debug("SCGA : set to 0 " + specimenCollectionGroupForm.getId());
}
boolean isOnChange = false;
String str = request.getParameter("isOnChange");
if (str != null)
{
if (str.equals("true"))
{
isOnChange = true;
}
}
//For Consent Tracking (Virender Mehta) - Start
//If radioButtonSelected = 1 then selected radio button is for Participant
//If radioButtonSelected = 2 then selected radio button is for Protocol Participant Identifier
int radioButtonSelected = 1;
//Id of Selected Participant or Protocol Participant Identifier
String selectedParticipantOrPPIdentifier_id = null;
// Radio button for Protocol Participant Identifier or Participant
String radioButtonSelectedForType = null;
String selectedCollectionProtocol_id = String.valueOf(specimenCollectionGroupForm.getCollectionProtocolId());
if (selectedCollectionProtocol_id.equalsIgnoreCase(Constants.SELECTED_COLLECTION_PROTOCOL_ID))
{
Map forwardToHashMap = (Map) request.getAttribute(Constants.FORWARD_TO_HASHMAP);
if (forwardToHashMap != null)
{
selectedCollectionProtocol_id = forwardToHashMap.get(Constants.COLLECTION_PROTOCOL_ID).toString();
selectedParticipantOrPPIdentifier_id = forwardToHashMap.get(Constants.PARTICIPANT_ID).toString();
radioButtonSelectedForType = Constants.PARTICIPANT_ID;
if (selectedParticipantOrPPIdentifier_id.equals("0"))
{
selectedParticipantOrPPIdentifier_id = forwardToHashMap.get(Constants.PARTICIPANT_PROTOCOL_ID).toString();
radioButtonSelectedForType = Constants.PARTICIPANT_PROTOCOL_ID;
}
}
}
else
{
radioButtonSelected = (int) specimenCollectionGroupForm.getRadioButtonForParticipant();
if (radioButtonSelected == 1)
{
selectedParticipantOrPPIdentifier_id = Long.toString(specimenCollectionGroupForm.getParticipantId());
radioButtonSelectedForType = Constants.PARTICIPANT_ID;
}
else
{
selectedParticipantOrPPIdentifier_id = specimenCollectionGroupForm.getProtocolParticipantIdentifier();
radioButtonSelectedForType = Constants.PARTICIPANT_PROTOCOL_ID;
}
}
CollectionProtocolRegistration collectionProtocolRegistration = null;
if (selectedParticipantOrPPIdentifier_id != null && !(selectedParticipantOrPPIdentifier_id.equalsIgnoreCase("0")))
{
//Get CollectionprotocolRegistration Object
collectionProtocolRegistration = getcollectionProtocolRegistrationObj(selectedParticipantOrPPIdentifier_id,
selectedCollectionProtocol_id, radioButtonSelectedForType);
}
else if (specimenCollectionGroupForm.getId() != 0)
{
//Get CollectionprotocolRegistration Object
SpecimenCollectionGroupBizLogic specimenCollectiongroupBizLogic = (SpecimenCollectionGroupBizLogic) BizLogicFactory.getInstance()
.getBizLogic(Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
collectionProtocolRegistration = (CollectionProtocolRegistration) specimenCollectiongroupBizLogic.retrieveAttribute(
SpecimenCollectionGroup.class.getName(), specimenCollectionGroupForm.getId(), "collectionProtocolRegistration");
}
User witness = null;
if (collectionProtocolRegistration.getId() != null)
{
witness = (User) bizLogicObj.retrieveAttribute(CollectionProtocolRegistration.class.getName(), collectionProtocolRegistration.getId(),
"consentWitness");
}
//User witness= userObj.getConsentWitness();
//Resolved Lazy
if (witness == null || witness.getFirstName() == null)
{
String witnessName = "";
specimenCollectionGroupForm.setWitnessName(witnessName);
}
else
{
String witnessFullName = witness.getLastName() + ", " + witness.getFirstName();
specimenCollectionGroupForm.setWitnessName(witnessFullName);
}
String getConsentDate = Utility
.parseDateToString(collectionProtocolRegistration.getConsentSignatureDate(), Constants.DATE_PATTERN_MM_DD_YYYY);
specimenCollectionGroupForm.setConsentDate(getConsentDate);
String getSignedConsentURL = Utility.toString(collectionProtocolRegistration.getSignedConsentDocumentURL());
specimenCollectionGroupForm.setSignedConsentUrl(getSignedConsentURL);
//Set witnessName,ConsentDate and SignedConsentURL
//Resolved Lazy ----collectionProtocolRegistration.getConsentTierResponseCollection()
Collection consentTierResponseCollection = (Collection) bizLogicObj.retrieveAttribute(CollectionProtocolRegistration.class.getName(),
collectionProtocolRegistration.getId(), "elements(consentTierResponseCollection)");
Set participantResponseSet = (Set) consentTierResponseCollection;
List participantResponseList = new ArrayList(participantResponseSet);
if (operation.equalsIgnoreCase(Constants.ADD))
{
ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
if (errors == null)
{
String protocolEventID = request.getParameter(Constants.PROTOCOL_EVENT_ID);
if (protocolEventID == null || protocolEventID.equalsIgnoreCase(Constants.FALSE))
{
Map tempMap = prepareConsentMap(participantResponseList);
specimenCollectionGroupForm.setConsentResponseForScgValues(tempMap);
}
}
specimenCollectionGroupForm.setConsentTierCounter(participantResponseList.size());
}
else
{
String scgID = String.valueOf(specimenCollectionGroupForm.getId());
SpecimenCollectionGroup specimenCollectionGroup = getSCGObj(scgID);
//List added for grid
List specimenDetails = new ArrayList();
getSpecimenDetails(specimenCollectionGroup, specimenDetails);
List columnList = columnNames();
//Resolved Lazy
//Collection consentResponse = specimenCollectionGroup.getCollectionProtocolRegistration().getConsentTierResponseCollection();
//Collection consentResponseStatuslevel= specimenCollectionGroup.getConsentTierStatusCollection();
Collection consentResponse = (Collection) bizLogicObj.retrieveAttribute(SpecimenCollectionGroup.class.getName(), specimenCollectionGroup
.getId(), "elements(collectionProtocolRegistration.consentTierResponseCollection)");
Collection consentResponseStatuslevel = (Collection) bizLogicObj.retrieveAttribute(SpecimenCollectionGroup.class.getName(),
specimenCollectionGroup.getId(), "elements(consentTierStatusCollection)");
Map tempMap = prepareSCGResponseMap(consentResponseStatuslevel, consentResponse);
specimenCollectionGroupForm.setConsentResponseForScgValues(tempMap);
specimenCollectionGroupForm.setConsentTierCounter(participantResponseList.size());
HttpSession session = request.getSession();
session.setAttribute(Constants.SPECIMEN_LIST, specimenDetails);
session.setAttribute(Constants.COLUMNLIST, columnList);
}
List specimenCollectionGroupResponseList = Utility.responceList(operation);
request.setAttribute(Constants.LIST_OF_SPECIMEN_COLLECTION_GROUP, specimenCollectionGroupResponseList);
String tabSelected = request.getParameter(Constants.SELECTED_TAB);
if (tabSelected != null)
{
request.setAttribute(Constants.SELECTED_TAB, tabSelected);
}
// For Consent Tracking (Virender Mehta) - End
// get list of Protocol title.
SpecimenCollectionGroupBizLogic bizLogic = (SpecimenCollectionGroupBizLogic) BizLogicFactory.getInstance().getBizLogic(
Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
//populating protocolist bean.
String sourceObjectName = CollectionProtocol.class.getName();
String[] displayNameFields = {"shortTitle"};
String valueField = Constants.SYSTEM_IDENTIFIER;
List list = bizLogic.getList(sourceObjectName, displayNameFields, valueField, true);
request.setAttribute(Constants.PROTOCOL_LIST, list);
Map<Long, String> cpIDTitleMap = Utility.getCPIDTitleMap();
request.setAttribute(Constants.CP_ID_TITLE_MAP, cpIDTitleMap);
//Populating the Site Type bean
sourceObjectName = Site.class.getName();
String[] siteDisplaySiteFields = {"name"};
list = bizLogic.getList(sourceObjectName, siteDisplaySiteFields, valueField, true);
request.setAttribute(Constants.SITELIST, list);
//Populating the participants registered to a given protocol
/**For Migration Start**/
// loadPaticipants(specimenCollectionGroupForm.getCollectionProtocolId() , bizLogic, request);
/**For Migration End**/
//Populating the protocol participants id registered to a given protocol
//By Abhishek Mehta -Performance Enhancement
//loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
String protocolParticipantId = specimenCollectionGroupForm.getProtocolParticipantIdentifier();
//Populating the participants Medical Identifier for a given participant
loadParticipantMedicalIdentifier(specimenCollectionGroupForm.getParticipantId(), bizLogic, request);
//Load Clinical status for a given study calander event point
String changeOn = request.getParameter(Constants.CHANGE_ON);
List calendarEventPointList = null;
if (changeOn != null && changeOn.equals(Constants.COLLECTION_PROTOCOL_ID))
{
calendarEventPointList = new ArrayList();
specimenCollectionGroupForm.setCollectionProtocolEventId(new Long(-1));
}
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(), bizLogic, request, specimenCollectionGroupForm);
calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(), Constants.SYSTEM_IDENTIFIER, new Long(
specimenCollectionGroupForm.getCollectionProtocolEventId()));
// The values of restrict checkbox and the number of specimen must alos populate in edit mode.
if ((isOnChange || operation.equalsIgnoreCase(Constants.EDIT)))
{
// Added by Vijay Pande. Method is created since code was repeating for SUBMITTED_FOR= "AddNew" || "Default" value.
setCalendarEventPoint(calendarEventPointList, request, specimenCollectionGroupForm);
}
// populating clinical Diagnosis field
CDE cde = CDEManager.getCDEManager().getCDE(Constants.CDE_NAME_CLINICAL_DIAGNOSIS);
CDEBizLogic cdeBizLogic = (CDEBizLogic) BizLogicFactory.getInstance().getBizLogic(Constants.CDE_FORM_ID);
List clinicalDiagnosisList = new ArrayList();
clinicalDiagnosisList.add(new NameValueBean(Constants.SELECT_OPTION, "" + Constants.SELECT_OPTION_VALUE));
cdeBizLogic.getFilteredCDE(cde.getPermissibleValues(), clinicalDiagnosisList);
request.setAttribute(Constants.CLINICAL_DIAGNOSIS_LIST, clinicalDiagnosisList);
// populating clinical Status field
// NameValueBean undefinedVal = new NameValueBean(Constants.UNDEFINED,Constants.UNDEFINED);
List clinicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CLINICAL_STATUS, null);
request.setAttribute(Constants.CLINICAL_STATUS_LIST, clinicalStatusList);
//Sets the activityStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.ACTIVITYSTATUSLIST, Constants.ACTIVITY_STATUS_VALUES);
//Sets the collectionStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.COLLECTIONSTATUSLIST, Constants.SCG_COLLECTION_STATUS_VALUES);
Logger.out.debug("CP ID in SCG Action======>" + specimenCollectionGroupForm.getCollectionProtocolId());
Logger.out.debug("Participant ID in SCG Action=====>" + specimenCollectionGroupForm.getParticipantId() + " "
+ specimenCollectionGroupForm.getProtocolParticipantIdentifier());
/**
* Name: Vijay Pande
* check for SUBMITTED_FOR with "AddNew" is added since while coming from specimen->scg->AddNew link for participant-> Register participant -> submit then the SUBMITTED_FOR is equal to "AddNew"
* If the flow is scg->AddNew link for participant-> Register participant -> submit then the SUBMITTED_FOR is equal to "Default"
*/
// -------called from Collection Protocol Registration start-------------------------------
if ((request.getAttribute(Constants.SUBMITTED_FOR) != null)
&& ((request.getAttribute(Constants.SUBMITTED_FOR).equals("Default")) || (request.getAttribute(Constants.SUBMITTED_FOR)
.equals(Constants.ADDNEW_LINK))))
{
Logger.out.debug("Populating CP and Participant in SCG ==== AddNew operation loop");
Long cprId = new Long(specimenCollectionGroupForm.getCollectionProtocolRegistrationId());
if (cprId != null)
{
List collectionProtocolRegistrationList = bizLogic.retrieve(CollectionProtocolRegistration.class.getName(),
Constants.SYSTEM_IDENTIFIER, cprId);
if (!collectionProtocolRegistrationList.isEmpty())
{
Object obj = collectionProtocolRegistrationList.get(0);
CollectionProtocolRegistration cpr = (CollectionProtocolRegistration) obj;
long cpID = cpr.getCollectionProtocol().getId().longValue();
long pID = cpr.getParticipant().getId().longValue();
String ppID = cpr.getProtocolParticipantIdentifier();
Logger.out.debug("cpID : " + cpID + " || pID : " + pID + " || ppID : " + ppID);
specimenCollectionGroupForm.setCollectionProtocolId(cpID);
//Populating the participants registered to a given protocol
/**For Migration Start**/
// loadPaticipants(cpID , bizLogic, request);
/**For Migration Start**/
//By Abhishek Mehta -Performance Enhancement
//loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
/**
* Name: Vijay Pande
* Reviewer Name: Aarti Sharma
* participant associated with collection protocol is explicitly retrived from DB since its lazy load property is true
*/
Participant cprParticipant = (Participant) bizLogic.retrieveAttribute(CollectionProtocolRegistration.class.getName(),
cpr.getId(), Constants.COLUMN_NAME_PARTICIPANT);
// set participant id in request. This is required only in CP based View since SpecimenTreeView.jsp is retrieveing participant id from request
if (cprParticipant.getId() != null)
{
request.setAttribute(Constants.CP_SEARCH_PARTICIPANT_ID, cprParticipant.getId().toString());
}
String firstName = Utility.toString(cprParticipant.getFirstName());
;
String lastName = Utility.toString(cprParticipant.getLastName());
String birthDate = Utility.toString(cprParticipant.getBirthDate());
String ssn = Utility.toString(cprParticipant.getSocialSecurityNumber());
if (firstName.trim().length() > 0 || lastName.trim().length() > 0 || birthDate.trim().length() > 0 || ssn.trim().length() > 0)
{
specimenCollectionGroupForm.setParticipantId(pID);
specimenCollectionGroupForm.setRadioButtonForParticipant(1);
specimenCollectionGroupForm.setParticipantName(lastName + ", " + firstName);
}
//Populating the protocol participants id registered to a given protocol
else if (cpr.getProtocolParticipantIdentifier() != null)
{
specimenCollectionGroupForm.setProtocolParticipantIdentifier(ppID);
specimenCollectionGroupForm.setRadioButtonForParticipant(2);
}
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(), bizLogic, request, specimenCollectionGroupForm);
//Load Clinical status for a given study calander event point
calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(), Constants.SYSTEM_IDENTIFIER, new Long(
specimenCollectionGroupForm.getCollectionProtocolEventId()));
if (isOnChange && !calendarEventPointList.isEmpty())
{
setCalendarEventPoint(calendarEventPointList, request, specimenCollectionGroupForm);
}
}
}
request.setAttribute(Constants.SUBMITTED_FOR, "Default");
}
//************* ForwardTo implementation *************
HashMap forwardToHashMap = (HashMap) request.getAttribute("forwardToHashMap");
if (forwardToHashMap != null)
{
/**
* Name: Falguni Sachde
* Reviewer Name:
* Attribute collectionProtocolName added to show Collection ProtocolName in Add mode only.
*/
Long collectionProtocolId = (Long) forwardToHashMap.get("collectionProtocolId");
String collectionProtocolName = (String) request.getSession().getAttribute("cpTitle");
if (collectionProtocolId == null && request.getParameter("cpId") != null && !request.getParameter("cpId").equals("null"))
{
collectionProtocolId = new Long(request.getParameter("cpId"));
}
Long participantId = (Long) forwardToHashMap.get("participantId");
String participantProtocolId = (String) forwardToHashMap.get("participantProtocolId");
specimenCollectionGroupForm.setCollectionProtocolId(collectionProtocolId.longValue());
specimenCollectionGroupForm.setCollectionProtocolName(collectionProtocolName);
/**
* Name : Deepti Shelar
* Bug id : 4216
* Patch id : 4216_1
* Description : populating list of ParticipantMedicalIdentifiers for given participant id
*/
loadParticipantMedicalIdentifier(participantId, bizLogic, request);
if (participantId != null && participantId.longValue() != 0)
{
//Populating the participants registered to a given protocol
/**For Migration Start**/
// loadPaticipants(collectionProtocolId.longValue(), bizLogic, request);
/**For Migration End**/
//By Abhishek Mehta -Performance Enhancement
//loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
specimenCollectionGroupForm.setParticipantId(participantId.longValue());
specimenCollectionGroupForm.setRadioButtonForParticipant(1);
request.setAttribute(Constants.CP_SEARCH_PARTICIPANT_ID, participantId.toString());
/**For Migration Start**/
List participantList = bizLogic.retrieve(Participant.class.getName(), Constants.SYSTEM_IDENTIFIER, Utility.toString(participantId));
if (participantList != null)
{
Participant participant = (Participant) participantList.get(0);
String firstName = "";
String lastName = "";
if (participant.getFirstName() != null)
{
firstName = participant.getFirstName();
}
if (participant.getLastName() != null)
{
lastName = participant.getLastName();
}
if (!firstName.equals("") && !lastName.equals(""))
{
specimenCollectionGroupForm.setParticipantName(lastName + ", " + firstName);
}
else if (lastName.equals("") && !firstName.equals(""))
{
specimenCollectionGroupForm.setParticipantName(participant.getFirstName());
}
else if (firstName.equals("") && !lastName.equals(""))
{
specimenCollectionGroupForm.setParticipantName(participant.getLastName());
}
}
/**For Migration End**/
/**
* Name : Deepti Shelar
* Reviewer Name : Sachin Lale
* Bug id : FutureSCG
* Patch Id : FutureSCG_1
* Description : setting participantProtocolId to form
*/
if (participantProtocolId == null)
{
participantProtocolId = getParticipantProtocolIdForCPAndParticipantId(participantId.toString(), collectionProtocolId.toString(),
bizLogic);
if (participantProtocolId != null)
{
specimenCollectionGroupForm.setProtocolParticipantIdentifier(participantProtocolId);
specimenCollectionGroupForm.setRadioButtonForParticipant(2);
}
}
}
else if (participantProtocolId != null)
{
//Populating the participants registered to a given protocol
/**For Migration Start**/
// loadPaticipants(collectionProtocolId.longValue(), bizLogic, request);
/**For Migration End**/
//By Abhishek Mehta -Performance Enhancement
//loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
specimenCollectionGroupForm.setProtocolParticipantIdentifier(participantProtocolId);
specimenCollectionGroupForm.setRadioButtonForParticipant(2);
String cpParticipantId = getParticipantIdForProtocolId(participantProtocolId, bizLogic);
if (cpParticipantId != null)
{
request.setAttribute(Constants.CP_SEARCH_PARTICIPANT_ID, cpParticipantId);
}
}
/**
* Patch Id : FutureSCG_3
* Description : Setting number of specimens and restricted checkbox
*/
/**
* Removing the above patch, as it no more required. Now the new CP based entry page takes care of this.
*/
Long cpeId = (Long) forwardToHashMap.get("COLLECTION_PROTOCOL_EVENT_ID");
if (cpeId != null)
{
specimenCollectionGroupForm.setCollectionProtocolEventId(cpeId);
/*List cpeList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(),Constants.SYSTEM_IDENTIFIER,cpeId);
if(!cpeList.isEmpty())
{
setNumberOfSpecimens(request, specimenCollectionGroupForm, cpeList);
}*/
}
//Bug 1915:SpecimenCollectionGroup.Study Calendar Event Point not populated when page is loaded through proceedTo
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(), bizLogic, request, specimenCollectionGroupForm);
//Load Clinical status for a given study calander event point
calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(), Constants.SYSTEM_IDENTIFIER, new Long(
specimenCollectionGroupForm.getCollectionProtocolEventId()));
if (!calendarEventPointList.isEmpty())
{
setCalendarEventPoint(calendarEventPointList, request, specimenCollectionGroupForm);
}
Logger.out.debug("CollectionProtocolID found in forwardToHashMap========>>>>>>" + collectionProtocolId);
Logger.out.debug("ParticipantID found in forwardToHashMap========>>>>>>" + participantId);
Logger.out.debug("ParticipantProtocolID found in forwardToHashMap========>>>>>>" + participantProtocolId);
}
//************* ForwardTo implementation *************
//Populate the group name field with default value in the form of
//<Collection Protocol Name>_<Participant ID>_<Group Id>
int groupNumber = bizLogic.getNextGroupNumber();
//Get the collection protocol title for the collection protocol Id selected
String collectionProtocolTitle = "";
String collectionProtocolName = "";
list = bizLogic.retrieve(CollectionProtocol.class.getName(), valueField, new Long(specimenCollectionGroupForm.getCollectionProtocolId()));
if (!list.isEmpty())
{
CollectionProtocol collectionProtocol = (CollectionProtocol) list.get(0);
collectionProtocolTitle = collectionProtocol.getTitle();
collectionProtocolName = (String) collectionProtocol.getShortTitle();
specimenCollectionGroupForm.setCollectionProtocolName(collectionProtocolName);
}
long groupParticipantId = specimenCollectionGroupForm.getParticipantId();
//check if the reset name link was clicked
String resetName = request.getParameter(Constants.RESET_NAME);
//Set the name to default if reset name link was clicked or page is loading for first time
//through add link or forward to link
if (forwardToHashMap != null || (specimenCollectionGroupForm.getName() != null && specimenCollectionGroupForm.getName().equals(""))
|| (resetName != null && resetName.equals("Yes")))
{
if (!collectionProtocolTitle.equals("")
&& (groupParticipantId > 0 || (protocolParticipantId != null && !protocolParticipantId.equals(""))))
{
//Poornima:Bug 2833 - Error thrown when adding a specimen collection group
//Max length of CP is 150 and Max length of SCG is 55, in Oracle the name does not truncate
//and it is giving error. So the title is truncated in case it is longer than 30 .
String maxCollTitle = collectionProtocolName;
if (collectionProtocolName.length() > Constants.COLLECTION_PROTOCOL_TITLE_LENGTH)
{
maxCollTitle = collectionProtocolName.substring(0, Constants.COLLECTION_PROTOCOL_TITLE_LENGTH - 1);
}
//During add operation the id to set in the default name is generated
if (operation.equals(Constants.ADD))
{
specimenCollectionGroupForm.setName(maxCollTitle + "_" + groupParticipantId + "_" + groupNumber);
}
//During edit operation the id to set in the default name using the id
else if (operation.equals(Constants.EDIT) && (resetName != null && resetName.equals("Yes")))
{
if (groupParticipantId > 0)
{
specimenCollectionGroupForm.setName(maxCollTitle + "_" + groupParticipantId + "_" + specimenCollectionGroupForm.getId());
}
else
{
specimenCollectionGroupForm.setName(maxCollTitle + "_" + protocolParticipantId + "_" + specimenCollectionGroupForm.getId());
}
}
}
}
request.setAttribute(Constants.PAGEOF, pageOf);
Logger.out.debug("page of in Specimen coll grp action:" + request.getParameter(Constants.PAGEOF));
// -------called from Collection Protocol Registration end -------------------------------
//Falguni:Performance Enhancement.
Long scgEntityId = null;
if (CatissueCoreCacheManager.getInstance().getObjectFromCache("scgEntityId") != null)
{
scgEntityId = (Long) CatissueCoreCacheManager.getInstance().getObjectFromCache("scgEntityId");
}
else
{
scgEntityId = AnnotationUtil.getEntityId(AnnotationConstants.ENTITY_NAME_SPECIMEN_COLLN_GROUP);
CatissueCoreCacheManager.getInstance().addObjectToCache("scgEntityId", scgEntityId);
}
request.setAttribute("scgEntityId", scgEntityId);
/**
* Name : Ashish Gupta
* Reviewer Name : Sachin Lale
* Bug ID: 2741
* Patch ID: 2741_11
* Description: Methods to set default events on SCG page
*/
setDefaultEvents(request, specimenCollectionGroupForm, operation);
request.setAttribute("scgForm", specimenCollectionGroupForm);
/* Bug ID: 4135
* Patch ID: 4135_2
* Description: Setting the ids in collection and received events associated with this scg
*/
//When opening in Edit mode, to set the ids of collection event parameters and received event parameters
if (specimenCollectionGroupForm.getId() != 0)
{
setEventsId(specimenCollectionGroupForm, bizLogic);
}
// set associated identified report id
Long reportId = getAssociatedIdentifiedReportId(specimenCollectionGroupForm.getId());
if (reportId == null)
{
reportId = new Long(-1);
}
else if (Utility.isQuarantined(reportId))
{
reportId = new Long(-2);
}
HttpSession session = request.getSession();
session.setAttribute(Constants.IDENTIFIED_REPORT_ID, reportId);
return mapping.findForward(pageOf);
}
/**
* @param specimenCollectionGroupForm
* @param bizLogic
* @throws DAOException
*/
private void setEventsId(SpecimenCollectionGroupForm specimenCollectionGroupForm, SpecimenCollectionGroupBizLogic bizLogic) throws DAOException
{
String scgId = "" + specimenCollectionGroupForm.getId();
List scglist = bizLogic.retrieve(SpecimenCollectionGroup.class.getName(), "id", scgId);
if (scglist != null && !scglist.isEmpty())
{
SpecimenCollectionGroup scg = (SpecimenCollectionGroup) scglist.get(0);
Collection eventsColl = scg.getSpecimenEventParametersCollection();
CollectionEventParameters collectionEventParameters = null;
ReceivedEventParameters receivedEventParameters = null;
if (eventsColl != null && !eventsColl.isEmpty())
{
Iterator iter = eventsColl.iterator();
while (iter.hasNext())
{
Object temp = iter.next();
if (temp instanceof CollectionEventParameters)
{
collectionEventParameters = (CollectionEventParameters) temp;
}
else if (temp instanceof ReceivedEventParameters)
{
receivedEventParameters = (ReceivedEventParameters) temp;
}
}
// Setting the ids
specimenCollectionGroupForm.setCollectionEventId(collectionEventParameters.getId().longValue());
specimenCollectionGroupForm.setReceivedEventId(receivedEventParameters.getId().longValue());
}
}
}
/**
* @param request
* @param specimenCollectionGroupForm
*/
private void setDefaultEvents(HttpServletRequest request, SpecimenCollectionGroupForm specimenCollectionGroupForm, String operation)
throws DAOException
{
setDateParameters(specimenCollectionGroupForm, request);
if (specimenCollectionGroupForm.getCollectionEventCollectionProcedure() == null)
{
specimenCollectionGroupForm.setCollectionEventCollectionProcedure((String) DefaultValueManager
.getDefaultValue(Constants.DEFAULT_COLLECTION_PROCEDURE));
}
if (specimenCollectionGroupForm.getCollectionEventContainer() == null)
{
specimenCollectionGroupForm.setCollectionEventContainer((String) DefaultValueManager.getDefaultValue(Constants.DEFAULT_CONTAINER));
}
if (specimenCollectionGroupForm.getReceivedEventReceivedQuality() == null)
{
specimenCollectionGroupForm.setReceivedEventReceivedQuality((String) DefaultValueManager
.getDefaultValue(Constants.DEFAULT_RECEIVED_QUALITY));
}
//setting the collector and receiver drop downs
setUserInForm(request, operation, specimenCollectionGroupForm);
//Setting the List for drop downs
setEventsListInRequest(request);
}
/**
* @param request
*/
private void setEventsListInRequest(HttpServletRequest request)
{
//setting the procedure
List procedureList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COLLECTION_PROCEDURE, null);
request.setAttribute(Constants.PROCEDURE_LIST, procedureList);
// set the container lists
List containerList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CONTAINER, null);
request.setAttribute(Constants.CONTAINER_LIST, containerList);
//setting the quality for received events
List qualityList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_RECEIVED_QUALITY, null);
request.setAttribute(Constants.RECEIVED_QUALITY_LIST, qualityList);
// Sets the hourList attribute to be used in the Add/Edit FrozenEventParameters Page.
request.setAttribute(Constants.HOUR_LIST, Constants.HOUR_ARRAY);
//Sets the minutesList attribute to be used in the Add/Edit FrozenEventParameters Page.
request.setAttribute(Constants.MINUTES_LIST, Constants.MINUTES_ARRAY);
}
/**
* @param request
* @param operation
* @param specimenCollectionGroupForm
* @throws DAOException
*/
private void setUserInForm(HttpServletRequest request, String operation, SpecimenCollectionGroupForm specimenCollectionGroupForm)
throws DAOException
{
UserBizLogic userBizLogic = (UserBizLogic) BizLogicFactory.getInstance().getBizLogic(Constants.USER_FORM_ID);
Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
SessionDataBean sessionData = getSessionData(request);
if (sessionData != null)
{
String user = sessionData.getLastName() + ", " + sessionData.getFirstName();
long collectionEventUserId = EventsUtil.getIdFromCollection(userCollection, user);
if (specimenCollectionGroupForm.getCollectionEventUserId() == 0)
{
specimenCollectionGroupForm.setCollectionEventUserId(collectionEventUserId);
}
if (specimenCollectionGroupForm.getReceivedEventUserId() == 0)
{
specimenCollectionGroupForm.setReceivedEventUserId(collectionEventUserId);
}
}
}
/**
* @param specimenForm
*/
private void setDateParameters(SpecimenCollectionGroupForm specimenForm, HttpServletRequest request)
{
// set the current Date and Time for the event.
Calendar cal = Calendar.getInstance();
//Collection Event fields
if (specimenForm.getCollectionEventdateOfEvent() == null)
{
if (request.getParameter("evtDate") != null)
{
specimenForm.setCollectionEventdateOfEvent(request.getParameter("evtDate"));
}
else
{
specimenForm.setCollectionEventdateOfEvent(Utility.parseDateToString(cal.getTime(), Constants.DATE_PATTERN_MM_DD_YYYY));
}
}
if (specimenForm.getCollectionEventTimeInHours() == null)
{
specimenForm.setCollectionEventTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (specimenForm.getCollectionEventTimeInMinutes() == null)
{
specimenForm.setCollectionEventTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
//ReceivedEvent Fields
if (specimenForm.getReceivedEventDateOfEvent() == null)
{
specimenForm.setReceivedEventDateOfEvent(Utility.parseDateToString(cal.getTime(), Constants.DATE_PATTERN_MM_DD_YYYY));
}
if (specimenForm.getReceivedEventTimeInHours() == null)
{
specimenForm.setReceivedEventTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (specimenForm.getReceivedEventTimeInMinutes() == null)
{
specimenForm.setReceivedEventTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
/**For Migration Start**/
/* private void loadPaticipants(long protocolID, IBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String [] displayParticipantFields = {"participant.id"};
String valueField = "participant."+Constants.SYSTEM_IDENTIFIER;
String whereColumnName[] = {"collectionProtocol."+Constants.SYSTEM_IDENTIFIER,"participant.id"};
String whereColumnCondition[];
Object[] whereColumnValue;
if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
{
whereColumnCondition = new String[]{"=","is not"};
whereColumnValue=new Object[]{new Long(protocolID),null};
}
else
{
// for ORACLE
whereColumnCondition = new String[]{"=",Constants.IS_NOT_NULL};
whereColumnValue=new Object[]{new Long(protocolID),""};
}
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = ", ";
List list = bizLogic.getList(sourceObjectName, displayParticipantFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, true);
//get list of Participant's names
valueField = Constants.SYSTEM_IDENTIFIER;
sourceObjectName = Participant.class.getName();
String[] participantsFields = {"lastName","firstName","birthDate","socialSecurityNumber"};
String[] whereColumnName2 = {"lastName","firstName","birthDate","socialSecurityNumber"};
String[] whereColumnCondition2 = {"!=","!=","is not","is not"};
Object[] whereColumnValue2 = {"","",null,null};
if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
{
whereColumnCondition2 = new String[]{"!=","!=","is not","is not"};
whereColumnValue2=new String[]{"","",null,null};
}
else
{
// for ORACLE
whereColumnCondition2 = new String[]{Constants.IS_NOT_NULL,Constants.IS_NOT_NULL,Constants.IS_NOT_NULL,Constants.IS_NOT_NULL};
whereColumnValue2=new String[]{"","","",""};
}
String joinCondition2 = Constants.OR_JOIN_CONDITION;
String separatorBetweenFields2 = ", ";
List listOfParticipants = bizLogic.getList(sourceObjectName, participantsFields, valueField, whereColumnName2,
whereColumnCondition2, whereColumnValue2, joinCondition2, separatorBetweenFields, false);
// removing blank participants from the list of Participants
list=removeBlankParticipant(list, listOfParticipants);
//Mandar bug id:1628 :- sort participant dropdown list
Collections.sort(list );
Logger.out.debug("Paticipants List"+list);
request.setAttribute(Constants.PARTICIPANT_LIST, list);
}
private List removeBlankParticipant(List list, List listOfParticipants)
{
List listOfActiveParticipant=new ArrayList();
for(int i=0; i<list.size(); i++)
{
NameValueBean nameValueBean =(NameValueBean)list.get(i);
if(Long.parseLong(nameValueBean.getValue()) == -1)
{
listOfActiveParticipant.add(list.get(i));
continue;
}
for(int j=0; j<listOfParticipants.size(); j++)
{
if(Long.parseLong(((NameValueBean)listOfParticipants.get(j)).getValue()) == -1)
continue;
NameValueBean participantsBean = (NameValueBean)listOfParticipants.get(j);
if( nameValueBean.getValue().equals(participantsBean.getValue()) )
{
listOfActiveParticipant.add(listOfParticipants.get(j));
break;
}
}
}
Logger.out.debug("No.Of Active Participants Registered with Protocol~~~~~~~~~~~~~~~~~~~~~~~>"+listOfActiveParticipant.size());
return listOfActiveParticipant;
}
*/
/**Commented by Abhishek Mehta
* Method to load protocol participant identifier number list
* @param protocolID
* @param bizLogic
* @param request
* @throws Exception
*/
/*private void loadPaticipantNumberList(long protocolID, IBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String displayParticipantNumberFields[] = {"protocolParticipantIdentifier"};
String valueField = "protocolParticipantIdentifier";
String whereColumnName[] = {"collectionProtocol."+Constants.SYSTEM_IDENTIFIER, "protocolParticipantIdentifier"};
String whereColumnCondition[];// = {"=","!="};
Object[] whereColumnValue;// = {new Long(protocolID),"null"};
// if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
// {
whereColumnCondition = new String[]{"=","!="};
whereColumnValue = new Object[]{new Long(protocolID),"null"};
// }
// else
// {
// whereColumnCondition = new String[]{"=","!=null"};
// whereColumnValue = new Object[]{new Long(protocolID),""};
// }
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayParticipantNumberFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, true);
Logger.out.debug("Paticipant Number List"+list);
request.setAttribute(Constants.PROTOCOL_PARTICIPANT_NUMBER_LIST, list);
}*/
/**
* Method to load list of collection protocol event point
* @param protocolID
* @param bizLogic
* @param request
* @param form
* @throws Exception
*/
private void loadCollectionProtocolEvent(long protocolID, IBizLogic bizLogic, HttpServletRequest request, SpecimenCollectionGroupForm form)
throws Exception
{
String sourceObjectName = CollectionProtocolEvent.class.getName();
String displayEventFields[] = {"studyCalendarEventPoint", "collectionPointLabel"};
String valueField = "id";
String whereColumnName[] = {"collectionProtocol." + Constants.SYSTEM_IDENTIFIER};
String whereColumnCondition[] = {"="};
Object[] whereColumnValue = {new Long(protocolID)};
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = ",";
List list = bizLogic.getList(sourceObjectName, displayEventFields, valueField, whereColumnName, whereColumnCondition, whereColumnValue,
joinCondition, separatorBetweenFields, false);
request.setAttribute(Constants.STUDY_CALENDAR_EVENT_POINT_LIST, list);
if (list.size() > 1 && form.getCollectionProtocolEventId() <= 0)
{
form.setCollectionProtocolEventId(new Long(((NameValueBean) list.get(1)).getValue()));
}
}
/**
* Method to load list of participant medical identifier
* @param participantID
* @param bizLogic
* @param request
* @throws Exception
*/
private void loadParticipantMedicalIdentifier(long participantID, IBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = ParticipantMedicalIdentifier.class.getName();
String displayEventFields[] = {"medicalRecordNumber"};
String valueField = Constants.SYSTEM_IDENTIFIER;
String whereColumnName[] = {"participant." + Constants.SYSTEM_IDENTIFIER, "medicalRecordNumber"};
String whereColumnCondition[] = {"=", "!="};
Object[] whereColumnValue = {new Long(participantID), "null"};
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayEventFields, valueField, whereColumnName, whereColumnCondition, whereColumnValue,
joinCondition, separatorBetweenFields, false);
request.setAttribute(Constants.PARTICIPANT_MEDICAL_IDNETIFIER_LIST, list);
}
/**
* Method to retrieve participant id from the protocol participant id
* @param participantProtocolId
* @param bizLogic
* @return
* @throws Exception
*/
private String getParticipantIdForProtocolId(String participantProtocolId, IBizLogic bizLogic) throws Exception
{
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String selectColumnName[] = {"participant.id"};
String whereColumnName[] = {"protocolParticipantIdentifier"};
String whereColumnCondition[] = {"="};
Object[] whereColumnValue = {participantProtocolId};
List participantList = bizLogic.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue,
Constants.AND_JOIN_CONDITION);
if (participantList != null && !participantList.isEmpty())
{
String participantId = ((Long) participantList.get(0)).toString();
return participantId;
}
return null;
}
/**
* Method to retrieve participant protocol identifier for given CP and participant id
* @param participantId
* @param cpId
* @param bizLogic
* @return
* @throws Exception
*/
private String getParticipantProtocolIdForCPAndParticipantId(String participantId, String cpId, IBizLogic bizLogic) throws Exception
{
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String selectColumnName[] = {"protocolParticipantIdentifier"};
String whereColumnName[] = {"participant.id", "collectionProtocol.id"};
String whereColumnCondition[] = {"=", "="};
Object[] whereColumnValue = {participantId, cpId};
List list = bizLogic.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue,
Constants.AND_JOIN_CONDITION);
if (list != null && !list.isEmpty())
{
Iterator iter = list.iterator();
while (iter.hasNext())
{
Object id = (Object) iter.next();
if (id != null)
{
return id.toString();
}
}
}
return null;
}
/**
* Method to set default values related to calendar event point list
* @param calendarEventPointList calendar event point list
* @param request object of HttpServletRequest
* @param specimenCollectionGroupForm object of specimenCollectionGroup action form
* @throws DAOException
*/
private void setCalendarEventPoint(List calendarEventPointList, HttpServletRequest request,
SpecimenCollectionGroupForm specimenCollectionGroupForm) throws DAOException
{
// Patch ID: Bug#3184_27
//By Abhishek Mehta
int numberOfSpecimen = 1;
if (!calendarEventPointList.isEmpty())
{
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent) calendarEventPointList.get(0);
//Set checkbox status depending upon the days of study calendar event point. If it is zero, then unset the restrict
//checkbox, otherwise set the restrict checkbox
Double studyCalendarEventPoint = collectionProtocolEvent.getStudyCalendarEventPoint();
if (studyCalendarEventPoint.doubleValue() == 0)
{
specimenCollectionGroupForm.setRestrictSCGCheckbox("false");
}
else
{
specimenCollectionGroupForm.setRestrictSCGCheckbox("true");
}
}
else if (calendarEventPointList.isEmpty())
{
//Set checkbox status
specimenCollectionGroupForm.setRestrictSCGCheckbox("false");
}
//Sets the value for number of specimen field on the specimen collection group page.
//Set the number of actual specimen requirements for validation purpose.
//This value is used in validate method of SpecimenCollectionGroupForm.java.
// request.setAttribute(Constants.NUMBER_OF_SPECIMEN_REQUIREMENTS, numberOfSpecimen + "");
}
//Consent Tracking Virender Mehta
/**
* @param idOfSelectedRadioButton Id for selected radio button.
* @param cp_id CollectionProtocolID CollectionProtocolID selected by dropdown
* @param indexType i.e Which Radio button is selected participantId or protocolParticipantIdentifier
* @return collectionProtocolRegistration CollectionProtocolRegistration object
*/
private CollectionProtocolRegistration getcollectionProtocolRegistrationObj(String idOfSelectedRadioButton, String cp_id, String indexType)
throws DAOException
{
CollectionProtocolRegistrationBizLogic collectionProtocolRegistrationBizLogic = (CollectionProtocolRegistrationBizLogic) BizLogicFactory
.getInstance().getBizLogic(Constants.COLLECTION_PROTOCOL_REGISTRATION_FORM_ID);
String[] colName = new String[2];
if (indexType.equalsIgnoreCase(Constants.PARTICIPANT_ID))
{
colName[0] = "participant.id";
colName[1] = "collectionProtocol.id";
}
else
{
colName[0] = "protocolParticipantIdentifier";
colName[1] = "collectionProtocol.id";
}
String[] colCondition = {"=", "="};
String[] val = new String[2];
val[0] = idOfSelectedRadioButton;
val[1] = cp_id;
List collProtRegObj = collectionProtocolRegistrationBizLogic.retrieve(CollectionProtocolRegistration.class.getName(), colName, colCondition,
val, null);
CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration) collProtRegObj.get(0);
return collectionProtocolRegistration;
}
/**
* For ConsentTracking Preparing consentResponseForScgValues for populating Dynamic contents on the UI
* @param partiResponseCollection This Containes the collection of ConsentTier Response at CPR level
* @param statusResponseCollection This Containes the collection of ConsentTier Response at Specimen level
* @return tempMap
*/
private Map prepareSCGResponseMap(Collection statusResponseCollection, Collection partiResponseCollection)
{
Map tempMap = new HashMap();
Long consentTierID;
Long consentID;
if (partiResponseCollection != null || statusResponseCollection != null)
{
int i = 0;
Iterator statusResponsIter = statusResponseCollection.iterator();
while (statusResponsIter.hasNext())
{
ConsentTierStatus consentTierstatus = (ConsentTierStatus) statusResponsIter.next();
consentTierID = consentTierstatus.getConsentTier().getId();
Iterator participantResponseIter = partiResponseCollection.iterator();
while (participantResponseIter.hasNext())
{
ConsentTierResponse consentTierResponse = (ConsentTierResponse) participantResponseIter.next();
consentID = consentTierResponse.getConsentTier().getId();
if (consentTierID.longValue() == consentID.longValue())
{
ConsentTier consent = consentTierResponse.getConsentTier();
String idKey = "ConsentBean:" + i + "_consentTierID";
String statementKey = "ConsentBean:" + i + "_statement";
String participantResponsekey = "ConsentBean:" + i + "_participantResponse";
String participantResponceIdKey = "ConsentBean:" + i + "_participantResponseID";
String scgResponsekey = "ConsentBean:" + i + "_specimenCollectionGroupLevelResponse";
String scgResponseIDkey = "ConsentBean:" + i + "_specimenCollectionGroupLevelResponseID";
tempMap.put(idKey, consent.getId());
tempMap.put(statementKey, consent.getStatement());
tempMap.put(participantResponsekey, consentTierResponse.getResponse());
tempMap.put(participantResponceIdKey, consentTierResponse.getId());
tempMap.put(scgResponsekey, consentTierstatus.getStatus());
tempMap.put(scgResponseIDkey, consentTierstatus.getId());
i++;
break;
}
}
}
return tempMap;
}
else
{
return null;
}
}
/**
* Prepare Map for Consent tiers
* @param participantResponseList This list will be iterated to map to populate participant Response status.
* @return tempMap
*/
private Map prepareConsentMap(List participantResponseList)
{
Map tempMap = new HashMap();
if (participantResponseList != null)
{
int i = 0;
Iterator consentResponseCollectionIter = participantResponseList.iterator();
while (consentResponseCollectionIter.hasNext())
{
ConsentTierResponse consentTierResponse = (ConsentTierResponse) consentResponseCollectionIter.next();
ConsentTier consent = consentTierResponse.getConsentTier();
String idKey = "ConsentBean:" + i + "_consentTierID";
String statementKey = "ConsentBean:" + i + "_statement";
String responseKey = "ConsentBean:" + i + "_participantResponse";
String participantResponceIdKey = "ConsentBean:" + i + "_participantResponseID";
String scgResponsekey = "ConsentBean:" + i + "_specimenCollectionGroupLevelResponse";
String scgResponseIDkey = "ConsentBean:" + i + "_specimenCollectionGroupLevelResponseID";
tempMap.put(idKey, consent.getId());
tempMap.put(statementKey, consent.getStatement());
tempMap.put(responseKey, consentTierResponse.getResponse());
tempMap.put(participantResponceIdKey, consentTierResponse.getId());
tempMap.put(scgResponsekey, consentTierResponse.getResponse());
tempMap.put(scgResponseIDkey, null);
i++;
}
}
return tempMap;
}
/**
* This function will return CollectionProtocolRegistration object
* @param scg_id Selected SpecimenCollectionGroup ID
* @return collectionProtocolRegistration
*/
private SpecimenCollectionGroup getSCGObj(String scg_id) throws DAOException
{
SpecimenCollectionGroupBizLogic specimenCollectionBizLogic = (SpecimenCollectionGroupBizLogic) BizLogicFactory.getInstance().getBizLogic(
Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
String colName = "id";
List getSCGIdFromDB = specimenCollectionBizLogic.retrieve(SpecimenCollectionGroup.class.getName(), colName, scg_id);
SpecimenCollectionGroup specimenCollectionGroupObject = (SpecimenCollectionGroup) getSCGIdFromDB.get(0);
return specimenCollectionGroupObject;
}
//Consent Tracking Virender Mehta
/**
* This function is used for retriving specimen from Specimen collection group Object
* @param specimenObj
* @param finalDataList
* @throws DAOException
*/
private void getSpecimenDetails(SpecimenCollectionGroup specimenCollectionGroupObj, List finalDataList) throws DAOException
{
IBizLogic bizLogic = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC);
Collection specimen = null;
if (specimenCollectionGroupObj.getId() != null)
{
specimen = (Collection) bizLogic.retrieveAttribute(SpecimenCollectionGroup.class.getName(), specimenCollectionGroupObj.getId(),
"elements(specimenCollection)");
}
//Collection specimen = specimenCollectionGroupObj.getSpecimenCollection();
Iterator specimenIterator = specimen.iterator();
while (specimenIterator.hasNext())
{
Specimen specimenObj = (Specimen) specimenIterator.next();
getDetailsOfSpecimen(specimenObj, finalDataList);
}
}
/**
* This function is used for retriving specimen and sub specimen's attributes.
* @param specimenObj
* @param finalDataList
* @throws DAOException
*/
private void getDetailsOfSpecimen(Specimen specimenObj, List finalDataList) throws DAOException
{
IBizLogic bizLogic = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC);
List specimenDetailList = new ArrayList();
if (specimenObj.getActivityStatus().equals(Constants.ACTIVITY_STATUS_ACTIVE))
{
specimenDetailList.add(specimenObj.getLabel());
specimenDetailList.add(specimenObj.getType());
if (specimenObj.getStorageContainer() == null)
{
specimenDetailList.add(Constants.VIRTUALLY_LOCATED);
}
else
{
StorageContainer storageContainer = (StorageContainer) bizLogic.retrieveAttribute(Specimen.class.getName(), specimenObj.getId(),
"storageContainer");
//specimenObj.getStorageContainer().getName()+": X-Axis-"+specimenObj.getPositionDimensionOne()+", Y-Axis-"+specimenObj.getPositionDimensionTwo();
String storageLocation = storageContainer.getName() + ": X-Axis-" + specimenObj.getPositionDimensionOne() + ", Y-Axis-"
+ specimenObj.getPositionDimensionTwo();
specimenDetailList.add(storageLocation);
}
specimenDetailList.add(specimenObj.getClassName());
finalDataList.add(specimenDetailList);
}
}
/**
* This function adds the columns to the List
* @return columnList
*/
public List columnNames()
{
List columnList = new ArrayList();
columnList.add(Constants.LABLE);
columnList.add(Constants.TYPE);
columnList.add(Constants.STORAGE_CONTAINER_LOCATION);
columnList.add(Constants.CLASS_NAME);
return columnList;
}
private Long getAssociatedIdentifiedReportId(Long scgId) throws DAOException
{
IdentifiedSurgicalPathologyReportBizLogic bizLogic = (IdentifiedSurgicalPathologyReportBizLogic) BizLogicFactory.getInstance().getBizLogic(
IdentifiedSurgicalPathologyReport.class.getName());
String sourceObjectName = IdentifiedSurgicalPathologyReport.class.getName();
String displayEventFields[] = {"id"};
String valueField = Constants.SYSTEM_IDENTIFIER;
String whereColumnName[] = {Constants.COLUMN_NAME_SCG_ID};
String whereColumnCondition[] = {"="};
Object[] whereColumnValue = {scgId};
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayEventFields, valueField, whereColumnName, whereColumnCondition, whereColumnValue,
joinCondition, separatorBetweenFields, false);
if (list != null && list.size() > 1)
{
NameValueBean nvBean = (NameValueBean) list.get(1);
return (new Long(nvBean.getValue()));
}
return null;
}
}
| *** empty log message ***
SVN-Revision: 11288
| WEB-INF/src/edu/wustl/catissuecore/action/SpecimenCollectionGroupAction.java | *** empty log message *** | <ide><path>EB-INF/src/edu/wustl/catissuecore/action/SpecimenCollectionGroupAction.java
<ide> import edu.wustl.common.util.logger.Logger;
<ide>
<ide> /**
<del> * SpecimenCollectionGroupAction initializes the fields in the
<add> * SpecimenCollectionGroupAction initializes the fields in the
<ide> * New Specimen Collection Group page.
<ide> * @author ajay_sharma
<ide> */
<ide> * @param response object of HttpServletResponse
<ide> * @throws Exception generic exception
<ide> */
<del> public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
<add> public ActionForward executeSecureAction(ActionMapping mapping,
<add> final ActionForm form, final HttpServletRequest request,
<add> final HttpServletResponse response)
<ide> throws Exception
<ide> {
<ide>
<ide> request.setAttribute(Constants.CP_SEARCH_PARTICIPANT_ID, cprParticipant.getId().toString());
<ide> }
<ide> String firstName = Utility.toString(cprParticipant.getFirstName());
<del> ;
<ide> String lastName = Utility.toString(cprParticipant.getLastName());
<ide> String birthDate = Utility.toString(cprParticipant.getBirthDate());
<ide> String ssn = Utility.toString(cprParticipant.getSocialSecurityNumber());
<ide> //Collection Event fields
<ide> if (specimenForm.getCollectionEventdateOfEvent() == null)
<ide> {
<del> if (request.getParameter("evtDate") != null)
<del> {
<del> specimenForm.setCollectionEventdateOfEvent(request.getParameter("evtDate"));
<del> }
<del> else
<del> {
<ide> specimenForm.setCollectionEventdateOfEvent(Utility.parseDateToString(cal.getTime(), Constants.DATE_PATTERN_MM_DD_YYYY));
<del> }
<ide> }
<ide> if (specimenForm.getCollectionEventTimeInHours() == null)
<ide> { |
|
Java | agpl-3.0 | 813ad92c5dcb26fdc860a48d2bbf0abaa06072ff | 0 | retest/recheck,retest/recheck | package de.retest.recheck.persistence.bin;
import static java.nio.file.Files.newInputStream;
import static java.nio.file.Files.newOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.objenesis.strategy.StdInstantiatorStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Registration;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.google.common.collect.TreeMultiset;
import de.javakaffee.kryoserializers.UnmodifiableCollectionsSerializer;
import de.retest.recheck.persistence.IncompatibleReportVersionException;
import de.retest.recheck.persistence.Persistable;
import de.retest.recheck.persistence.Persistence;
import de.retest.recheck.util.FileUtil;
import de.retest.recheck.util.VersionProvider;
import net.jpountz.lz4.LZ4FrameInputStream;
import net.jpountz.lz4.LZ4FrameOutputStream;
public class KryoPersistence<T extends Persistable> implements Persistence<T> {
private static final String OLD_RECHECK_VERSION = "an old recheck version (pre 1.5.0)";
private static final Logger logger = LoggerFactory.getLogger( KryoPersistence.class );
private final Kryo kryo;
private final String version;
public KryoPersistence() {
this( createKryo(), VersionProvider.RETEST_VERSION );
}
/**
* Testing only!
*
* @param kryo
* {@code Kryo} instance to use.
* @param version
* recheck version to use.
*/
KryoPersistence( final Kryo kryo, final String version ) {
this.kryo = kryo;
this.version = version;
}
private static Kryo createKryo() {
final Kryo kryo = new Kryo();
kryo.setInstantiatorStrategy( new Kryo.DefaultInstantiatorStrategy( new StdInstantiatorStrategy() ) );
final Registration registration = kryo.getRegistration( TreeMultiset.class );
registration.setInstantiator( TreeMultiset::create );
UnmodifiableCollectionsSerializer.registerSerializers( kryo );
return kryo;
}
@Override
public void save( final URI identifier, final T element ) throws IOException {
final Path path = Paths.get( identifier );
final File file = path.toFile();
FileUtil.ensureFolder( path.toFile() );
try ( final Output output = new Output( new LZ4FrameOutputStream( newOutputStream( path ) ) ) ) {
output.writeString( version );
logger.debug( "Writing {} to {}. Do not write to same identifier or interrupt until done.", element,
identifier );
kryo.writeClassAndObject( output, element );
logger.debug( "Done writing {} to {}", element, identifier );
} catch ( final Error | Exception anything ) {
logger.error(
"Error writing to file {}. Deleting what has been written to not leave corrupt file behind...",
identifier, anything );
FileUtils.deleteQuietly( file );
throw anything;
}
}
@SuppressWarnings( "unchecked" )
@Override
public T load( final URI identifier ) throws IOException {
final Path path = Paths.get( identifier );
String writerVersion = null;
try ( final Input input = new Input( new LZ4FrameInputStream( newInputStream( path ) ) ) ) {
writerVersion = input.readString();
return (T) kryo.readClassAndObject( input );
} catch ( final Exception e ) {
if ( version.equals( writerVersion ) ) {
throw e;
}
if ( isUnknownFormat( writerVersion ) ) {
writerVersion = OLD_RECHECK_VERSION;
}
throw new IncompatibleReportVersionException( writerVersion, version, identifier, e );
}
}
private static final Pattern VERSION_CHARS = Pattern.compile( "[\\w\\.\\{\\}\\$]+" );
private static boolean isUnknownFormat( final String writerVersion ) {
if ( writerVersion == null ) {
return true;
}
final Matcher m = VERSION_CHARS.matcher( writerVersion );
return !m.matches();
}
}
| src/main/java/de/retest/recheck/persistence/bin/KryoPersistence.java | package de.retest.recheck.persistence.bin;
import static java.nio.file.Files.newInputStream;
import static java.nio.file.Files.newOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.objenesis.strategy.StdInstantiatorStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Registration;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.google.common.collect.TreeMultiset;
import de.javakaffee.kryoserializers.UnmodifiableCollectionsSerializer;
import de.retest.recheck.persistence.IncompatibleReportVersionException;
import de.retest.recheck.persistence.Persistable;
import de.retest.recheck.persistence.Persistence;
import de.retest.recheck.util.FileUtil;
import de.retest.recheck.util.VersionProvider;
import net.jpountz.lz4.LZ4FrameInputStream;
import net.jpountz.lz4.LZ4FrameOutputStream;
public class KryoPersistence<T extends Persistable> implements Persistence<T> {
private static final String OLD_RECHECK_VERSION = "an old recheck version (pre 1.5.0)";
private static final Logger logger = LoggerFactory.getLogger( KryoPersistence.class );
private final Kryo kryo;
private final String version;
public KryoPersistence() {
this( createKryo(), VersionProvider.RETEST_VERSION );
}
/**
* Testing only!
*
* @param kryo
* {@code Kryo} instance to use.
* @param version
* recheck version to use.
*/
KryoPersistence( final Kryo kryo, final String version ) {
this.kryo = kryo;
this.version = version;
}
private static Kryo createKryo() {
final Kryo kryo = new Kryo();
kryo.setInstantiatorStrategy( new Kryo.DefaultInstantiatorStrategy( new StdInstantiatorStrategy() ) );
final Registration registration = kryo.getRegistration( TreeMultiset.class );
registration.setInstantiator( TreeMultiset::create );
UnmodifiableCollectionsSerializer.registerSerializers( kryo );
return kryo;
}
@Override
public void save( final URI identifier, final T element ) throws IOException {
final Path path = Paths.get( identifier );
final File file = path.toFile();
FileUtil.ensureFolder( path.toFile() );
try ( final Output output = new Output( new LZ4FrameOutputStream( newOutputStream( path ) ) ) ) {
output.writeString( version );
logger.debug( "Writing {} to {}. Do not write to same identifier or interrupt until done.", element,
identifier );
kryo.writeClassAndObject( output, element );
logger.debug( "Done writing {} to {}", element, identifier );
} catch ( Error | Exception anything ) {
logger.error(
"Error writing to file {}. Deleting what has been written to not leave corrupt file behind...",
identifier, anything );
FileUtils.deleteQuietly( file );
throw anything;
}
}
@SuppressWarnings( "unchecked" )
@Override
public T load( final URI identifier ) throws IOException {
final Path path = Paths.get( identifier );
String writerVersion = null;
try ( final Input input = new Input( new LZ4FrameInputStream( newInputStream( path ) ) ) ) {
writerVersion = input.readString();
return (T) kryo.readClassAndObject( input );
} catch ( final Exception e ) {
if ( version.equals( writerVersion ) ) {
throw e;
}
if ( isUnknownFormat( writerVersion ) ) {
writerVersion = OLD_RECHECK_VERSION;
// TODO Remove after release of 1.6.0
try ( final Input secondInput = new Input( newInputStream( path ) ) ) {
return (T) kryo.readClassAndObject( secondInput );
}
// remove until here
}
throw new IncompatibleReportVersionException( writerVersion, version, identifier, e );
}
}
private static final Pattern VERSION_CHARS = Pattern.compile( "[\\w\\.\\{\\}\\$]+" );
private static boolean isUnknownFormat( final String writerVersion ) {
if ( writerVersion == null ) {
return true;
}
final Matcher m = VERSION_CHARS.matcher( writerVersion );
return !m.matches();
}
}
| As stated in the TODO, remove the fallback loading
for reports pre 1.5.0
| src/main/java/de/retest/recheck/persistence/bin/KryoPersistence.java | As stated in the TODO, remove the fallback loading | <ide><path>rc/main/java/de/retest/recheck/persistence/bin/KryoPersistence.java
<ide> identifier );
<ide> kryo.writeClassAndObject( output, element );
<ide> logger.debug( "Done writing {} to {}", element, identifier );
<del> } catch ( Error | Exception anything ) {
<add> } catch ( final Error | Exception anything ) {
<ide> logger.error(
<ide> "Error writing to file {}. Deleting what has been written to not leave corrupt file behind...",
<ide> identifier, anything );
<ide> }
<ide> if ( isUnknownFormat( writerVersion ) ) {
<ide> writerVersion = OLD_RECHECK_VERSION;
<del> // TODO Remove after release of 1.6.0
<del> try ( final Input secondInput = new Input( newInputStream( path ) ) ) {
<del> return (T) kryo.readClassAndObject( secondInput );
<del> }
<del> // remove until here
<ide> }
<ide> throw new IncompatibleReportVersionException( writerVersion, version, identifier, e );
<ide> } |
|
Java | mit | error: pathspec 'src/test/java/me/moodcat/database/controllers/SongDAOTest.java' did not match any file(s) known to git
| 3c7e8353e3b76b7648c2f61f0965a52c2698141c | 1 | MoodCat/MoodCat.me-Core,MoodCat/MoodCat.me-Core | package me.moodcat.database.controllers;
import com.google.inject.Inject;
import me.moodcat.database.DatabaseTestModule;
import me.moodcat.database.entities.Artist;
import me.moodcat.database.entities.Song;
import org.jukito.JukitoRunner;
import org.jukito.UseModules;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
/**
* This methods test to persist a Song
*
* @author Jan-Willem Gmelig Meyling
*/
@RunWith(JukitoRunner.class)
@UseModules(DatabaseTestModule.class)
public class SongDAOTest {
private final static String ARTIST_NAME = "Fall Out Boy";
private final static String SONG_NAME = "Thanks for the Memories";
/**
* The ArtistDAO.
*/
@Inject
private ArtistDAO artistDAO;
/**
* The SongDAO.
*/
@Inject
private SongDAO songDAO;
/**
* The artist.
*/
private Artist artist;
/**
* Create artist.
*/
@Before
public void createArist() {
artist = new Artist();
artist.setName(ARTIST_NAME);
artistDAO.persist(artist);
Artist actual = artistDAO.findByName(ARTIST_NAME);
assertEquals(artist, actual);
}
/**
* Persist a song with data.
*/
@Test
public void persistSongWithData() {
final Song song = new Song();
song.setName(SONG_NAME);
song.setArtist(artist);
songDAO.persist(song);
Song actual = songDAO.findByName(SONG_NAME);
assertEquals(song, actual);
}
}
| src/test/java/me/moodcat/database/controllers/SongDAOTest.java | Restored SongDAOTest
| src/test/java/me/moodcat/database/controllers/SongDAOTest.java | Restored SongDAOTest | <ide><path>rc/test/java/me/moodcat/database/controllers/SongDAOTest.java
<add>package me.moodcat.database.controllers;
<add>
<add>import com.google.inject.Inject;
<add>import me.moodcat.database.DatabaseTestModule;
<add>import me.moodcat.database.entities.Artist;
<add>import me.moodcat.database.entities.Song;
<add>import org.jukito.JukitoRunner;
<add>import org.jukito.UseModules;
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>
<add>import java.io.IOException;
<add>import static org.junit.Assert.assertEquals;
<add>
<add>/**
<add> * This methods test to persist a Song
<add> *
<add> * @author Jan-Willem Gmelig Meyling
<add> */
<add>@RunWith(JukitoRunner.class)
<add>@UseModules(DatabaseTestModule.class)
<add>public class SongDAOTest {
<add>
<add> private final static String ARTIST_NAME = "Fall Out Boy";
<add> private final static String SONG_NAME = "Thanks for the Memories";
<add>
<add> /**
<add> * The ArtistDAO.
<add> */
<add> @Inject
<add> private ArtistDAO artistDAO;
<add>
<add> /**
<add> * The SongDAO.
<add> */
<add> @Inject
<add> private SongDAO songDAO;
<add>
<add> /**
<add> * The artist.
<add> */
<add> private Artist artist;
<add>
<add> /**
<add> * Create artist.
<add> */
<add> @Before
<add> public void createArist() {
<add> artist = new Artist();
<add> artist.setName(ARTIST_NAME);
<add> artistDAO.persist(artist);
<add>
<add> Artist actual = artistDAO.findByName(ARTIST_NAME);
<add> assertEquals(artist, actual);
<add> }
<add>
<add> /**
<add> * Persist a song with data.
<add> */
<add> @Test
<add> public void persistSongWithData() {
<add> final Song song = new Song();
<add> song.setName(SONG_NAME);
<add> song.setArtist(artist);
<add> songDAO.persist(song);
<add>
<add> Song actual = songDAO.findByName(SONG_NAME);
<add> assertEquals(song, actual);
<add> }
<add>
<add>} |
|
JavaScript | mit | a0828ddee34b86d35165518a4a8ded48a98d3b93 | 0 | mjw56/surfsup,mjw56/surfsup | (function(){
'use strict';
var chai = require('chai'),
should = chai.should(),
expect = chai.expect,
spies = require('chai-spies'),
SurfsUp = require('../bin/index'),
su = new SurfsUp();
describe('surfsup', function(){
it('should allow you to query for local weather', function(done){
su.getLocalWeather({ q: 'Teahupoo, Tahiti', format: 'json' }).then(function(response) {
expect(response).to.not.be.undefined;
expect(response.data).to.be.defined;
done();
}).catch(function(err) {
done(err);
});
});
it('should not break if undefined passed to local weather method', function(done){
su.getLocalWeather().then(function(response) {
expect(response).to.equal('<?xml version="1.0" encoding="UTF-8"?><data><error><msg>Unable to find any matching weather location to the query submitted!</msg></error></data>');
done();
}).catch(function(err) {
done(err);
});
});
it('should allow you to query for ski and mountain weather', function(done){
su.getSkiMountainWeather({ q: 'Salt Lake City', format: 'json' }).then(function(response) {
expect(response).to.not.be.undefined;
expect(response.data).to.be.defined;
done();
}).catch(function(err) {
done(err);
});
});
it('should not break if undefined passed to ski mountainer method', function(done){
su.getSkiMountainWeather().then(function(response) {
expect(response).to.equal('<?xml version="1.0" encoding="UTF-8"?><data><error><msg>Unable to find any matching weather location to the query submitted!</msg></error></data>');
done();
}).catch(function(err) {
done(err);
});
});
it('should allow you to query for marine weather', function(done) {
su.getMarineWeather({ q: '-17.840208, -149.270001', format: 'json' }).then(function(response) {
expect(response).to.not.be.undefined;
expect(response.data).to.be.defined;
done();
}).catch(function(err) {
done(err);
});
});
it('should not break if undefined passed to local weather method', function(done){
su.getMarineWeather().then(function(response) {
expect(response).to.equal('<?xml version="1.0" encoding="UTF-8"?><data><request><type>Unknown</type><query /></request><nearest_area /></data>');
done();
}).catch(function(err) {
done(err);
});
});
it('should allow you to search for time zone data', function() {
});
});
})();
| tests/index.js | (function(){
'use strict';
var chai = require('chai'),
should = chai.should(),
expect = chai.expect,
spies = require('chai-spies'),
SurfsUp = require('../bin/index'),
su = new SurfsUp();
describe('surfsup', function(){
it('should allow you to query for local weather', function(done){
su.getLocalWeather({ q: 'Teahupoo, Tahiti', format: 'json' }).then(function(response) {
expect(response).to.not.be.undefined;
expect(response.data).to.be.defined;
done();
}).catch(function(err) {
done(err);
});
});
it('should not break if undefined passed to local weather method', function(done){
su.getLocalWeather().then(function(response) {
expect(response).to.equal('<?xml version="1.0" encoding="UTF-8"?><data><error><msg>Unable to find any matching weather location to the query submitted!</msg></error></data>');
done();
}).catch(function(err) {
done(err);
});
});
it('should allow you to query for ski and mountain weather', function(){
});
it('should allow you to query for marine weather', function(done) {
su.getMarineWeather({ q: '-17.840208, -149.270001', format: 'json' }).then(function(response) {
expect(response).to.not.be.undefined;
expect(response.data).to.be.defined;
done();
}).catch(function(err) {
done(err);
});
});
it('should not break if undefined passed to local weather method', function(done){
su.getMarineWeather().then(function(response) {
expect(response).to.equal('<?xml version="1.0" encoding="UTF-8"?><data><request><type>Unknown</type><query /></request><nearest_area /></data>');
done();
}).catch(function(err) {
done(err);
});
});
it('should allow you to search for time zone data', function() {
});
});
})();
| added tests for ski mountain method
| tests/index.js | added tests for ski mountain method | <ide><path>ests/index.js
<ide>
<ide> });
<ide>
<del> it('should allow you to query for ski and mountain weather', function(){
<add> it('should allow you to query for ski and mountain weather', function(done){
<add> su.getSkiMountainWeather({ q: 'Salt Lake City', format: 'json' }).then(function(response) {
<add> expect(response).to.not.be.undefined;
<add> expect(response.data).to.be.defined;
<add> done();
<add> }).catch(function(err) {
<add> done(err);
<add> });
<add> });
<add>
<add> it('should not break if undefined passed to ski mountainer method', function(done){
<add>
<add> su.getSkiMountainWeather().then(function(response) {
<add> expect(response).to.equal('<?xml version="1.0" encoding="UTF-8"?><data><error><msg>Unable to find any matching weather location to the query submitted!</msg></error></data>');
<add> done();
<add> }).catch(function(err) {
<add> done(err);
<add> });
<ide>
<ide> });
<ide> |
|
Java | apache-2.0 | 5b0da5ae422c9d8adb4f9c26b4847d1c394cca37 | 0 | reportportal/service-api,reportportal/service-api,reportportal/service-api,reportportal/service-api,reportportal/service-api | /*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.ws.controller;
import com.epam.ta.reportportal.dao.WidgetRepository;
import com.epam.ta.reportportal.entity.widget.Widget;
import com.epam.ta.reportportal.ws.BaseMvcTest;
import com.epam.ta.reportportal.ws.model.EntryCreatedRS;
import com.epam.ta.reportportal.ws.model.widget.ContentParameters;
import com.epam.ta.reportportal.ws.model.widget.WidgetPreviewRQ;
import com.epam.ta.reportportal.ws.model.widget.WidgetRQ;
import com.epam.ta.reportportal.ws.model.widget.WidgetResource;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MvcResult;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* @author <a href="mailto:[email protected]">Ihar Kahadouski</a>
*/
@Sql("/db/shareable/shareable-fill.sql")
class WidgetControllerTest extends BaseMvcTest {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private WidgetRepository widgetRepository;
@Test
void createWidgetPositive() throws Exception {
WidgetRQ rq = new WidgetRQ();
rq.setName("widget");
rq.setDescription("description");
rq.setWidgetType("oldLineChart");
ContentParameters contentParameters = new ContentParameters();
contentParameters.setContentFields(Arrays.asList("number", "name", "user", "statistics$defects$automation_bug$AB002"));
contentParameters.setItemsCount(50);
rq.setFilterIds(Collections.singletonList(3L));
rq.setContentParameters(contentParameters);
rq.setShare(true);
final MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/widget").with(token(oAuthHelper.getDefaultToken()))
.content(objectMapper.writeValueAsBytes(rq))
.contentType(APPLICATION_JSON)).andExpect(status().isCreated()).andReturn();
final EntryCreatedRS entryCreatedRS = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), EntryCreatedRS.class);
final Optional<Widget> optionalWidget = widgetRepository.findById(entryCreatedRS.getId());
assertTrue(optionalWidget.isPresent());
assertEquals("widget", optionalWidget.get().getName());
assertEquals("description", optionalWidget.get().getDescription());
}
@Test
void getWidgetPositive() throws Exception {
mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/widget/10").with(token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk());
}
@Test
void updateWidgetPositive() throws Exception {
final WidgetRQ rq = new WidgetRQ();
rq.setName("updated");
rq.setDescription("updated");
rq.setWidgetType("activityStream");
rq.setShare(false);
final ContentParameters contentParameters = new ContentParameters();
contentParameters.setContentFields(Arrays.asList("number", "start_time", "user"));
contentParameters.setItemsCount(50);
rq.setContentParameters(contentParameters);
mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/widget/12").with(token(oAuthHelper.getDefaultToken()))
.content(objectMapper.writeValueAsBytes(rq))
.contentType(APPLICATION_JSON)).andExpect(status().isOk());
final Optional<Widget> optionalWidget = widgetRepository.findById(12L);
assertTrue(optionalWidget.isPresent());
assertEquals("updated", optionalWidget.get().getName());
assertEquals("updated", optionalWidget.get().getDescription());
}
@Test
void updateNonExistingWidget() throws Exception {
WidgetRQ rq = new WidgetRQ();
rq.setName("name");
rq.setWidgetType("oldLineChart");
rq.setShare(false);
mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/widget/100").with(token(oAuthHelper.getDefaultToken()))
.content(objectMapper.writeValueAsBytes(rq))
.contentType(APPLICATION_JSON)).andExpect(status().isNotFound());
}
@Test
void updateWidgetWithDuplicatedName() throws Exception {
final WidgetRQ rq = new WidgetRQ();
rq.setName("LAUNCH STATISTICS");
rq.setDescription("updated");
rq.setWidgetType("activityStream");
rq.setShare(false);
final ContentParameters contentParameters = new ContentParameters();
contentParameters.setContentFields(Arrays.asList("number", "start_time", "user"));
contentParameters.setItemsCount(50);
rq.setContentParameters(contentParameters);
mockMvc.perform(put(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken()))
.content(objectMapper.writeValueAsBytes(rq))
.contentType(APPLICATION_JSON)).andExpect(status().isConflict());
}
@Test
void getSharedWidgetsListPositive() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/shared").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk());
}
@Test
void searchSharedWidgetsListPositive() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/shared/search?term=ch").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk());
}
@Test
void getWidgetNamesPositive() throws Exception {
mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/widget/names/all").with(token(oAuthHelper.getDefaultToken())))
.andExpect(status().is(200));
}
@Test
void getWidgetPreview() throws Exception {
WidgetPreviewRQ request = new WidgetPreviewRQ();
request.setWidgetType("launchStatistics");
final ContentParameters contentParameters = new ContentParameters();
final HashMap<String, Object> widgetOptions = new HashMap<>();
widgetOptions.put("timeline", "WEEK");
contentParameters.setWidgetOptions(widgetOptions);
contentParameters.setItemsCount(20);
contentParameters.setContentFields(Arrays.asList(
"statistics$executions$total",
"statistics$executions$passed",
"statistics$executions$failed",
"statistics$executions$skipped"
));
request.setContentParameters(contentParameters);
request.setFilterIds(Collections.singletonList(4L));
mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/widget/preview").with(token(oAuthHelper.getDefaultToken()))
.contentType(APPLICATION_JSON)
.content(objectMapper.writeValueAsBytes(request))).andExpect(status().isOk());
}
@Sql("/db/widget/launch-statistics.sql")
@Test
void getLaunchStatisticsWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launch stats"))
.andExpect(jsonPath("$.widgetType").value("launchStatistics"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/not-passed.sql")
@Test
void getNotPassedWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("not passed"))
.andExpect(jsonPath("$.widgetType").value("notPassed"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].values.*").value("60.0"));
}
@Sql("/db/widget/not-passed.sql")
@Test
void getEmptyContentNotPassedWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/launches-comparison-chart.sql")
@Test
void getLaunchesComparisonWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launch comparison"))
.andExpect(jsonPath("$.widgetType").value("launchesComparisonChart"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("33.33"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("33.33"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("33.33"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("60.0"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("40.0"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5.0"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].values.statistics$defects$product_bug$pb001").value("33.33"))
.andExpect(jsonPath("$.content.result[1].values.statistics$defects$to_investigate$ti001").value("66.67"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$failed").value("60.0"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$passed").value("20.0"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$skipped").value("20.0"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5.0"));
}
@Sql("/db/widget/launches-comparison-chart.sql")
@Test
void getEmptyContentLaunchesComparisonWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launch comparison"))
.andExpect(jsonPath("$.widgetType").value("launchesComparisonChart"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/launches-duration-chart.sql")
@Test
void getLaunchesDurationWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launches duration"))
.andExpect(jsonPath("$.widgetType").value("launchesDurationChart"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].duration").value("540000"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].duration").value("660000"));
}
@Sql("/db/widget/launches-duration-chart.sql")
@Test
void getEmptyContentLaunchesDurationWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launches duration"))
.andExpect(jsonPath("$.widgetType").value("launchesDurationChart"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/bug-trend.sql")
@Test
void getBugTrendWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("bug trend"))
.andExpect(jsonPath("$.widgetType").value("bugTrend"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$total").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$total").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$total").value("1"))
.andExpect(jsonPath("$.content.result[0].values.total").value("3"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].values.statistics$defects$product_bug$total").value("1"))
.andExpect(jsonPath("$.content.result[1].values.statistics$defects$to_investigate$total").value("2"))
.andExpect(jsonPath("$.content.result[1].values.total").value("3"));
}
@Sql("/db/widget/launches-table.sql")
@Test
void getLaunchesTableWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launches table"))
.andExpect(jsonPath("$.widgetType").value("launchesTable"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$skipped").value("1"))
.andExpect(jsonPath("$.content.result[0].values.status").value("FAILED"))
.andExpect(jsonPath("$.content.result[0].values.description").value("desc"))
.andExpect(jsonPath("$.content.result[0].values.user").value("superadmin"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("1"))
.andReturn();
}
@Sql("/db/widget/launches-table.sql")
@Test
void getEmptyContentLaunchesTableWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launches table"))
.andExpect(jsonPath("$.widgetType").value("launchesTable"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/top-test-cases.sql")
@Test
void getTopTestCasesWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("top test cases"))
.andExpect(jsonPath("$.widgetType").value("topTestCases"))
.andExpect(jsonPath("$.content.latestLaunch.name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].name").value("test item 5"))
.andExpect(jsonPath("$.content.result[0].total").value("1"))
.andExpect(jsonPath("$.content.result[1].name").value("test item 2"))
.andExpect(jsonPath("$.content.result[1].total").value("1"))
.andExpect(jsonPath("$.content.result[2].name").value("test item 3"))
.andExpect(jsonPath("$.content.result[2].total").value("1"));
}
@Sql("/db/widget/top-test-cases.sql")
@Test
void getEmptyContentTopTestCasesWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("top test cases"))
.andExpect(jsonPath("$.widgetType").value("topTestCases"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/top-test-cases.sql")
@Test
void getTopTestCasesWidgetWithNotExistLaunch() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isNotFound());
}
@Sql("/db/widget/top-test-cases.sql")
@Test
void getTopTestCasesIncludeMethodsWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("top test cases"))
.andExpect(jsonPath("$.widgetType").value("topTestCases"))
.andExpect(jsonPath("$.content.latestLaunch.name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].name").value("test item 5"))
.andExpect(jsonPath("$.content.result[0].total").value("1"))
.andExpect(jsonPath("$.content.result[1].name").value("test item 2"))
.andExpect(jsonPath("$.content.result[1].total").value("1"))
.andExpect(jsonPath("$.content.result[2].name").value("test item 3"))
.andExpect(jsonPath("$.content.result[2].total").value("1"));
}
@Sql("/db/widget/flaky-test-cases.sql")
@Test
void getFlakyTestCasesWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("flaky test cases"))
.andExpect(jsonPath("$.widgetType").value("flakyTestCases"))
.andExpect(jsonPath("$.content.latestLaunch.name").value("test launch"))
.andExpect(jsonPath("$.content.flaky[0].flakyCount").value("1"))
.andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4"));
}
@Sql("/db/widget/flaky-test-cases.sql")
@Test
void getFlakyTestCasesWidgetWithNotExistLaunch() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isNotFound());
}
@Sql("/db/widget/flaky-test-cases.sql")
@Test
void getEmptyContentFlakyTestCasesWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("flaky test cases"))
.andExpect(jsonPath("$.widgetType").value("flakyTestCases"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/flaky-test-cases.sql")
@Test
void getFlakyTestCasesWithIncludeMethodsWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("flaky test cases"))
.andExpect(jsonPath("$.widgetType").value("flakyTestCases"))
.andExpect(jsonPath("$.content.latestLaunch.name").value("test launch"))
.andExpect(jsonPath("$.content.flaky[0].flakyCount").value("1"))
.andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4"));
}
@Sql("/db/widget/cases-trend.sql")
@Test
void getCasesTrendWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("cases trend"))
.andExpect(jsonPath("$.widgetType").value("casesTrend"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].number").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].number").value("2"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/cases-trend.sql")
@Test
void getCasesTrendWidgetWithTimeline() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("cases trend"))
.andExpect(jsonPath("$.widgetType").value("casesTrend"))
.andExpect(jsonPath("$.content.result.*.name").value("test launch"))
.andExpect(jsonPath("$.content.result.*.number").value(2))
.andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/cases-trend.sql")
@Test
void getEmptyContentCasesTrendWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("cases trend"))
.andExpect(jsonPath("$.widgetType").value("casesTrend"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/cases-trend.sql")
@Test
void getCasesTrendWidgetWithWrongTimeLineOption() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/7").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("cases trend"))
.andExpect(jsonPath("$.widgetType").value("casesTrend"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].number").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].number").value("2"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/cases-trend.sql")
@Test
void getCasesTrendWidgetWithDescOrdering() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/8").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("cases trend"))
.andExpect(jsonPath("$.widgetType").value("casesTrend"))
.andExpect(jsonPath("$.content.result.*.name").value("test launch"))
.andExpect(jsonPath("$.content.result.*.number").value(2))
.andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/passing-rate-per-launch.sql")
@Test
void getPassingRatePerLaunchWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("passing rate per launch"))
.andExpect(jsonPath("$.widgetType").value("passingRatePerLaunch"))
.andExpect(jsonPath("$.content.result.passed").value("1"))
.andExpect(jsonPath("$.content.result.total").value("5"))
.andReturn();
}
@Sql("/db/widget/passing-rate-per-launch.sql")
@Test
void getEmptyContentPassingRatePerLaunchWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("passing rate per launch"))
.andExpect(jsonPath("$.widgetType").value("passingRatePerLaunch"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/passing-rate-per-launch.sql")
@Test
void getPassingRatePerLaunchWidgetWithNotExistLaunchName() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isNotFound());
}
@Sql("/db/widget/passing-rate-summary.sql")
@Test
void getPassingRateSummaryWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("passing rate summary"))
.andExpect(jsonPath("$.widgetType").value("passingRateSummary"))
.andExpect(jsonPath("$.content.result.passed").value("3"))
.andExpect(jsonPath("$.content.result.total").value("10"));
}
@Sql("/db/widget/passing-rate-summary.sql")
@Test
void getEmptyContentPassingRateSummaryWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/old-line-chart.sql")
@Test
void getOldLineChartWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("old line chart"))
.andExpect(jsonPath("$.widgetType").value("oldLineChart"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/old-line-chart.sql")
@Test
void getEmptyContentOldLineChartWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("old line chart"))
.andExpect(jsonPath("$.widgetType").value("oldLineChart"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/old-line-chart.sql")
@Test
void getOldLineChartWithTimeLineWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("old line chart"))
.andExpect(jsonPath("$.widgetType").value("oldLineChart"))
.andExpect(jsonPath("$.content.result.*.values.statistics$defects$automation_bug$ab001").value("1.0"))
.andExpect(jsonPath("$.content.result.*.values.statistics$defects$product_bug$pb001").value("1.0"))
.andExpect(jsonPath("$.content.result.*.values.statistics$defects$automation_bug$ab001").value("1.0"))
.andExpect(jsonPath("$.content.result.*.values.statistics$executions$failed").value("3.0"))
.andExpect(jsonPath("$.content.result.*.values.statistics$executions$passed").value("2.0"))
.andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5.0"));
}
@Sql("/db/widget/old-line-chart.sql")
@Test
void getEmptyContentOldLineChartWithTimeLineWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("old line chart"))
.andExpect(jsonPath("$.widgetType").value("oldLineChart"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/old-line-chart.sql")
@Test
void getOldLineChartWidgetWithIncorrectTimeLine() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/7").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("old line chart"))
.andExpect(jsonPath("$.widgetType").value("oldLineChart"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/investigated-trend.sql")
@Test
void getInvestigatedTrendWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("investigated trend"))
.andExpect(jsonPath("$.widgetType").value("investigatedTrend"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].number").value("1"))
.andExpect(jsonPath("$.content.result[0].values.toInvestigate").value("33.33"))
.andExpect(jsonPath("$.content.result[0].values.investigated").value("66.67"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].number").value("2"))
.andExpect(jsonPath("$.content.result[1].values.toInvestigate").value("66.67"))
.andExpect(jsonPath("$.content.result[1].values.investigated").value("33.33"));
}
//Waiting for fix
@Disabled
@Sql("/db/widget/investigated-trend.sql")
@Test
void getInvestigatedTrendWidgetWithTimeline() throws Exception {
MvcResult mvcResult = mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("investigated trend"))
.andExpect(jsonPath("$.widgetType").value("investigatedTrend"))
.andReturn();
WidgetResource response = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), new TypeReference<WidgetResource>() {
});
System.out.println();
}
@Sql("/db/widget/unique-bug-table.sql")
@Test
void getUniqueBugTableWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("unique bug table"))
.andExpect(jsonPath("$.widgetType").value("uniqueBugTable"))
.andExpect(jsonPath("$.content.result.ticket1[0].itemId").value(2))
.andExpect(jsonPath("$.content.result.ticket1[0].submitter").value("superadmin"))
.andExpect(jsonPath("$.content.result.ticket1[0].itemName").value("test item 2"))
.andExpect(jsonPath("$.content.result.ticket1[0].url").value("http:/example.com/ticket1"))
.andExpect(jsonPath("$.content.result.ticket1[0].launchId").value(1));
}
@Sql("/db/widget/unique-bug-table.sql")
@Test
void getEmptyContentUniqueBugTableWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("unique bug table"))
.andExpect(jsonPath("$.widgetType").value("uniqueBugTable"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/most-time-consuming.sql")
@Test
void getMostTimeConsumingWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("most time consuming"))
.andExpect(jsonPath("$.widgetType").value("mostTimeConsuming"))
.andExpect(jsonPath("$.content.result[0].name").value("test item 3"))
.andExpect(jsonPath("$.content.result[0].duration").value("337.0"))
.andExpect(jsonPath("$.content.result[1].name").value("test item 5"))
.andExpect(jsonPath("$.content.result[1].duration").value("251.0"))
.andExpect(jsonPath("$.content.result[2].name").value("test item 2"))
.andExpect(jsonPath("$.content.result[2].duration").value("192.0"))
.andExpect(jsonPath("$.content.result[3].name").value("test item 1"))
.andExpect(jsonPath("$.content.result[3].duration").value("165.0"))
.andExpect(jsonPath("$.content.result[4].name").value("test item 4"))
.andExpect(jsonPath("$.content.result[4].duration").value("87.0"));
}
@Sql("/db/widget/most-time-consuming.sql")
@Test
void getEmptyContentMostTimeConsumingWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("most time consuming"))
.andExpect(jsonPath("$.widgetType").value("mostTimeConsuming"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/most-time-consuming.sql")
@Test
void getMostTimeConsumingWidgetWithNotExistLaunch() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isNotFound());
}
@Sql("/db/widget/most-time-consuming.sql")
@Test
void getMostTimeConsumingWidgetWithIncludeMethods() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("most time consuming"))
.andExpect(jsonPath("$.widgetType").value("mostTimeConsuming"))
.andExpect(jsonPath("$.content.result[0].name").value("test item 3"))
.andExpect(jsonPath("$.content.result[0].duration").value("337.0"))
.andExpect(jsonPath("$.content.result[1].name").value("test item 5"))
.andExpect(jsonPath("$.content.result[1].duration").value("251.0"))
.andExpect(jsonPath("$.content.result[2].name").value("test item 2"))
.andExpect(jsonPath("$.content.result[2].duration").value("192.0"))
.andExpect(jsonPath("$.content.result[3].name").value("test item 1"))
.andExpect(jsonPath("$.content.result[3].duration").value("165.0"))
.andExpect(jsonPath("$.content.result[4].name").value("test item 4"))
.andExpect(jsonPath("$.content.result[4].duration").value("87.0"));
}
@Sql("/db/widget/overall-statistics.sql")
@Test
void getOverallStatisticsWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("overall statistics"))
.andExpect(jsonPath("$.widgetType").value("overallStatistics"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/overall-statistics.sql")
@Test
void getEmptyContentOverallStatisticsWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("overall statistics"))
.andExpect(jsonPath("$.widgetType").value("overallStatistics")).andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/activity-stream.sql")
@Test
void getActivityStreamWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("activity stream"))
.andExpect(jsonPath("$.widgetType").value("activityStream"))
.andExpect(jsonPath("$.content.result[0].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[0].actionType").value("startLaunch"))
.andExpect(jsonPath("$.content.result[0].objectType").value("LAUNCH"))
.andExpect(jsonPath("$.content.result[1].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[1].actionType").value("updateItem"))
.andExpect(jsonPath("$.content.result[1].objectType").value("ITEM"))
.andExpect(jsonPath("$.content.result[2].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[2].actionType").value("deleteLaunch"))
.andExpect(jsonPath("$.content.result[2].objectType").value("LAUNCH"));
}
@Sql("/db/widget/activity-stream.sql")
@Test
void getEmptyContentActivityStreamWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("activity stream"))
.andExpect(jsonPath("$.widgetType").value("activityStream"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/activity-stream.sql")
@Test
void getActivityStreamWidgetWithNotExistUser() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isNotFound());
}
@Sql("/db/widget/activity-stream.sql")
@Test
void getActivityStreamWidgetWithEmptyUserOption() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("activity stream"))
.andExpect(jsonPath("$.widgetType").value("activityStream"))
.andExpect(jsonPath("$.content.result[0].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[0].actionType").value("startLaunch"))
.andExpect(jsonPath("$.content.result[0].objectType").value("LAUNCH"))
.andExpect(jsonPath("$.content.result[1].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[1].actionType").value("updateItem"))
.andExpect(jsonPath("$.content.result[1].objectType").value("ITEM"))
.andExpect(jsonPath("$.content.result[2].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[2].actionType").value("deleteLaunch"))
.andExpect(jsonPath("$.content.result[2].objectType").value("LAUNCH"));
}
@Sql("/db/widget/product-status.sql")
@Test
void getProductStatusGroupedByLaunchWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("product status"))
.andExpect(jsonPath("$.widgetType").value("productStatus"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].number").value("1"))
.andExpect(jsonPath("$.content.result[0].attributes").isNotEmpty())
.andExpect(jsonPath("$.content.result[0].passingRate").value("40.0"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].number").value("2"))
.andExpect(jsonPath("$.content.result[1].attributes").doesNotExist())
.andExpect(jsonPath("$.content.result[1].passingRate").value("20.0"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$executions$passed").value("3"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$executions$skipped").value("1"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$defects$to_investigate$ti001").value("3"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$defects$product_bug$pb001").value("2"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$defects$automation_bug$ab001").value("1"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$executions$failed").value("6"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$executions$total").value("10"))
.andExpect(jsonPath("$.content.result[2].averagePassingRate").value("30.0"));
}
@Sql("/db/widget/product-status.sql")
@Test
void getEmptyContentProductStatusGroupedByLaunchWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("product status"))
.andExpect(jsonPath("$.widgetType").value("productStatus"))
.andExpect(jsonPath("$.content").isEmpty());
}
} | src/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerTest.java | /*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.ws.controller;
import com.epam.ta.reportportal.dao.WidgetRepository;
import com.epam.ta.reportportal.entity.widget.Widget;
import com.epam.ta.reportportal.ws.BaseMvcTest;
import com.epam.ta.reportportal.ws.model.EntryCreatedRS;
import com.epam.ta.reportportal.ws.model.widget.ContentParameters;
import com.epam.ta.reportportal.ws.model.widget.WidgetPreviewRQ;
import com.epam.ta.reportportal.ws.model.widget.WidgetRQ;
import com.epam.ta.reportportal.ws.model.widget.WidgetResource;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MvcResult;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* @author <a href="mailto:[email protected]">Ihar Kahadouski</a>
*/
@Sql("/db/shareable/shareable-fill.sql")
class WidgetControllerTest extends BaseMvcTest {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private WidgetRepository widgetRepository;
@Test
void createWidgetPositive() throws Exception {
WidgetRQ rq = new WidgetRQ();
rq.setName("widget");
rq.setDescription("description");
rq.setWidgetType("oldLineChart");
ContentParameters contentParameters = new ContentParameters();
contentParameters.setContentFields(Arrays.asList("number", "name", "user", "statistics$defects$automation_bug$AB002"));
contentParameters.setItemsCount(50);
rq.setFilterIds(Collections.singletonList(3L));
rq.setContentParameters(contentParameters);
rq.setShare(true);
final MvcResult mvcResult = mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/widget").with(token(oAuthHelper.getDefaultToken()))
.content(objectMapper.writeValueAsBytes(rq))
.contentType(APPLICATION_JSON)).andExpect(status().isCreated()).andReturn();
final EntryCreatedRS entryCreatedRS = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), EntryCreatedRS.class);
final Optional<Widget> optionalWidget = widgetRepository.findById(entryCreatedRS.getId());
assertTrue(optionalWidget.isPresent());
assertEquals("widget", optionalWidget.get().getName());
assertEquals("description", optionalWidget.get().getDescription());
}
@Test
void getWidgetPositive() throws Exception {
mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/widget/10").with(token(oAuthHelper.getDefaultToken()))).andExpect(status().isOk());
}
@Test
void updateWidgetPositive() throws Exception {
final WidgetRQ rq = new WidgetRQ();
rq.setName("updated");
rq.setDescription("updated");
rq.setWidgetType("activityStream");
rq.setShare(false);
final ContentParameters contentParameters = new ContentParameters();
contentParameters.setContentFields(Arrays.asList("number", "start_time", "user"));
contentParameters.setItemsCount(50);
rq.setContentParameters(contentParameters);
mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/widget/12").with(token(oAuthHelper.getDefaultToken()))
.content(objectMapper.writeValueAsBytes(rq))
.contentType(APPLICATION_JSON)).andExpect(status().isOk());
final Optional<Widget> optionalWidget = widgetRepository.findById(12L);
assertTrue(optionalWidget.isPresent());
assertEquals("updated", optionalWidget.get().getName());
assertEquals("updated", optionalWidget.get().getDescription());
}
@Test
void updateNonExistingWidget() throws Exception {
WidgetRQ rq = new WidgetRQ();
rq.setName("name");
rq.setWidgetType("oldLineChart");
rq.setShare(false);
mockMvc.perform(put(DEFAULT_PROJECT_BASE_URL + "/widget/100").with(token(oAuthHelper.getDefaultToken()))
.content(objectMapper.writeValueAsBytes(rq))
.contentType(APPLICATION_JSON)).andExpect(status().isNotFound());
}
@Test
void updateWidgetWithDuplicatedName() throws Exception {
final WidgetRQ rq = new WidgetRQ();
rq.setName("LAUNCH STATISTICS");
rq.setDescription("updated");
rq.setWidgetType("activityStream");
rq.setShare(false);
final ContentParameters contentParameters = new ContentParameters();
contentParameters.setContentFields(Arrays.asList("number", "start_time", "user"));
contentParameters.setItemsCount(50);
rq.setContentParameters(contentParameters);
mockMvc.perform(put(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken()))
.content(objectMapper.writeValueAsBytes(rq))
.contentType(APPLICATION_JSON)).andExpect(status().isConflict());
}
@Test
void getSharedWidgetsListPositive() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/shared").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk());
}
@Test
void searchSharedWidgetsListPositive() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/shared/search?term=ch").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk());
}
@Test
void getWidgetNamesPositive() throws Exception {
mockMvc.perform(get(DEFAULT_PROJECT_BASE_URL + "/widget/names/all").with(token(oAuthHelper.getDefaultToken())))
.andExpect(status().is(200));
}
@Test
void getWidgetPreview() throws Exception {
WidgetPreviewRQ request = new WidgetPreviewRQ();
request.setWidgetType("launchStatistics");
final ContentParameters contentParameters = new ContentParameters();
final HashMap<String, Object> widgetOptions = new HashMap<>();
widgetOptions.put("timeline", "WEEK");
contentParameters.setWidgetOptions(widgetOptions);
contentParameters.setItemsCount(20);
contentParameters.setContentFields(Arrays.asList(
"statistics$executions$total",
"statistics$executions$passed",
"statistics$executions$failed",
"statistics$executions$skipped"
));
request.setContentParameters(contentParameters);
request.setFilterIds(Collections.singletonList(4L));
mockMvc.perform(post(DEFAULT_PROJECT_BASE_URL + "/widget/preview").with(token(oAuthHelper.getDefaultToken()))
.contentType(APPLICATION_JSON)
.content(objectMapper.writeValueAsBytes(request))).andExpect(status().isOk());
}
@Sql("/db/widget/launch-statistics.sql")
@Test
void getLaunchStatisticsWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launch stats"))
.andExpect(jsonPath("$.widgetType").value("launchStatistics"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/not-passed.sql")
@Test
void getNotPassedWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("not passed"))
.andExpect(jsonPath("$.widgetType").value("notPassed"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].values.*").value("60.0"));
}
@Sql("/db/widget/not-passed.sql")
@Test
void getEmptyContentNotPassedWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/launches-comparison-chart.sql")
@Test
void getLaunchesComparisonWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launch comparison"))
.andExpect(jsonPath("$.widgetType").value("launchesComparisonChart"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("33.33"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("33.33"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("33.33"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("60.0"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("40.0"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5.0"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].values.statistics$defects$product_bug$pb001").value("33.33"))
.andExpect(jsonPath("$.content.result[1].values.statistics$defects$to_investigate$ti001").value("66.67"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$failed").value("60.0"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$passed").value("20.0"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$skipped").value("20.0"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5.0"));
}
@Sql("/db/widget/launches-comparison-chart.sql")
@Test
void getEmptyContentLaunchesComparisonWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launch comparison"))
.andExpect(jsonPath("$.widgetType").value("launchesComparisonChart"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/launches-duration-chart.sql")
@Test
void getLaunchesDurationWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launches duration"))
.andExpect(jsonPath("$.widgetType").value("launchesDurationChart"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].duration").value("540000"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].duration").value("660000"));
}
@Sql("/db/widget/launches-duration-chart.sql")
@Test
void getEmptyContentLaunchesDurationWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launches duration"))
.andExpect(jsonPath("$.widgetType").value("launchesDurationChart"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/bug-trend.sql")
@Test
void getBugTrendWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("bug trend"))
.andExpect(jsonPath("$.widgetType").value("bugTrend"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$total").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$total").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$total").value("1"))
.andExpect(jsonPath("$.content.result[0].values.total").value("3"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].values.statistics$defects$product_bug$total").value("1"))
.andExpect(jsonPath("$.content.result[1].values.statistics$defects$to_investigate$total").value("2"))
.andExpect(jsonPath("$.content.result[1].values.total").value("3"));
}
@Sql("/db/widget/launches-table.sql")
@Test
void getLaunchesTableWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launches table"))
.andExpect(jsonPath("$.widgetType").value("launchesTable"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$skipped").value("1"))
.andExpect(jsonPath("$.content.result[0].values.status").value("FAILED"))
.andExpect(jsonPath("$.content.result[0].values.description").value("desc"))
.andExpect(jsonPath("$.content.result[0].values.user").value("superadmin"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("1"))
.andReturn();
}
@Sql("/db/widget/launches-table.sql")
@Test
void getEmptyContentLaunchesTableWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("launches table"))
.andExpect(jsonPath("$.widgetType").value("launchesTable"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/top-test-cases.sql")
@Test
void getTopTestCasesWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("top test cases"))
.andExpect(jsonPath("$.widgetType").value("topTestCases"))
.andExpect(jsonPath("$.content.latestLaunch.name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].name").value("test item 5"))
.andExpect(jsonPath("$.content.result[0].total").value("1"))
.andExpect(jsonPath("$.content.result[1].name").value("test item 2"))
.andExpect(jsonPath("$.content.result[1].total").value("1"))
.andExpect(jsonPath("$.content.result[2].name").value("test item 3"))
.andExpect(jsonPath("$.content.result[2].total").value("1"));
}
@Sql("/db/widget/top-test-cases.sql")
@Test
void getEmptyContentTopTestCasesWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("top test cases"))
.andExpect(jsonPath("$.widgetType").value("topTestCases"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/top-test-cases.sql")
@Test
void getTopTestCasesWidgetWithNotExistLaunch() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isNotFound());
}
@Sql("/db/widget/top-test-cases.sql")
@Test
void getTopTestCasesIncludeMethodsWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("top test cases"))
.andExpect(jsonPath("$.widgetType").value("topTestCases"))
.andExpect(jsonPath("$.content.latestLaunch.name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].name").value("test item 5"))
.andExpect(jsonPath("$.content.result[0].total").value("1"))
.andExpect(jsonPath("$.content.result[1].name").value("test item 2"))
.andExpect(jsonPath("$.content.result[1].total").value("1"))
.andExpect(jsonPath("$.content.result[2].name").value("test item 3"))
.andExpect(jsonPath("$.content.result[2].total").value("1"));
}
@Sql("/db/widget/flaky-test-cases.sql")
@Test
void getFlakyTestCasesWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("flaky test cases"))
.andExpect(jsonPath("$.widgetType").value("flakyTestCases"))
.andExpect(jsonPath("$.content.latestLaunch.name").value("test launch"))
.andExpect(jsonPath("$.content.flaky[0].flakyCount").value("1"))
.andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4"))
.andExpect(jsonPath("$.content.flaky[1].flakyCount").value("0"))
.andExpect(jsonPath("$.content.flaky[1].itemName").value("test item 1"))
.andExpect(jsonPath("$.content.flaky[2].flakyCount").value("0"))
.andExpect(jsonPath("$.content.flaky[2].itemName").value("test item 2"))
.andExpect(jsonPath("$.content.flaky[3].flakyCount").value("0"))
.andExpect(jsonPath("$.content.flaky[3].itemName").value("test item 3"))
.andExpect(jsonPath("$.content.flaky[4].flakyCount").value("0"))
.andExpect(jsonPath("$.content.flaky[4].itemName").value("test item 5"));
}
@Sql("/db/widget/flaky-test-cases.sql")
@Test
void getFlakyTestCasesWidgetWithNotExistLaunch() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isNotFound());
}
@Sql("/db/widget/flaky-test-cases.sql")
@Test
void getEmptyContentFlakyTestCasesWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("flaky test cases"))
.andExpect(jsonPath("$.widgetType").value("flakyTestCases"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/flaky-test-cases.sql")
@Test
void getFlakyTestCasesWithIncludeMethodsWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("flaky test cases"))
.andExpect(jsonPath("$.widgetType").value("flakyTestCases"))
.andExpect(jsonPath("$.content.latestLaunch.name").value("test launch"))
.andExpect(jsonPath("$.content.flaky[0].flakyCount").value("1"))
.andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4"))
.andExpect(jsonPath("$.content.flaky[1].flakyCount").value("0"))
.andExpect(jsonPath("$.content.flaky[1].itemName").value("test item 1"))
.andExpect(jsonPath("$.content.flaky[2].flakyCount").value("0"))
.andExpect(jsonPath("$.content.flaky[2].itemName").value("test item 2"))
.andExpect(jsonPath("$.content.flaky[3].flakyCount").value("0"))
.andExpect(jsonPath("$.content.flaky[3].itemName").value("test item 3"))
.andExpect(jsonPath("$.content.flaky[4].flakyCount").value("0"))
.andExpect(jsonPath("$.content.flaky[4].itemName").value("test item 5"));
}
@Sql("/db/widget/cases-trend.sql")
@Test
void getCasesTrendWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("cases trend"))
.andExpect(jsonPath("$.widgetType").value("casesTrend"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].number").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].number").value("2"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/cases-trend.sql")
@Test
void getCasesTrendWidgetWithTimeline() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("cases trend"))
.andExpect(jsonPath("$.widgetType").value("casesTrend"))
.andExpect(jsonPath("$.content.result.*.name").value("test launch"))
.andExpect(jsonPath("$.content.result.*.number").value(2))
.andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/cases-trend.sql")
@Test
void getEmptyContentCasesTrendWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("cases trend"))
.andExpect(jsonPath("$.widgetType").value("casesTrend"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/cases-trend.sql")
@Test
void getCasesTrendWidgetWithWrongTimeLineOption() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/7").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("cases trend"))
.andExpect(jsonPath("$.widgetType").value("casesTrend"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].number").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].number").value("2"))
.andExpect(jsonPath("$.content.result[1].values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/cases-trend.sql")
@Test
void getCasesTrendWidgetWithDescOrdering() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/8").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("cases trend"))
.andExpect(jsonPath("$.widgetType").value("casesTrend"))
.andExpect(jsonPath("$.content.result.*.name").value("test launch"))
.andExpect(jsonPath("$.content.result.*.number").value(2))
.andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/passing-rate-per-launch.sql")
@Test
void getPassingRatePerLaunchWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("passing rate per launch"))
.andExpect(jsonPath("$.widgetType").value("passingRatePerLaunch"))
.andExpect(jsonPath("$.content.result.passed").value("1"))
.andExpect(jsonPath("$.content.result.total").value("5"))
.andReturn();
}
@Sql("/db/widget/passing-rate-per-launch.sql")
@Test
void getEmptyContentPassingRatePerLaunchWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("passing rate per launch"))
.andExpect(jsonPath("$.widgetType").value("passingRatePerLaunch"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/passing-rate-per-launch.sql")
@Test
void getPassingRatePerLaunchWidgetWithNotExistLaunchName() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isNotFound());
}
@Sql("/db/widget/passing-rate-summary.sql")
@Test
void getPassingRateSummaryWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("passing rate summary"))
.andExpect(jsonPath("$.widgetType").value("passingRateSummary"))
.andExpect(jsonPath("$.content.result.passed").value("3"))
.andExpect(jsonPath("$.content.result.total").value("10"));
}
@Sql("/db/widget/passing-rate-summary.sql")
@Test
void getEmptyContentPassingRateSummaryWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/old-line-chart.sql")
@Test
void getOldLineChartWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("old line chart"))
.andExpect(jsonPath("$.widgetType").value("oldLineChart"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/old-line-chart.sql")
@Test
void getEmptyContentOldLineChartWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("old line chart"))
.andExpect(jsonPath("$.widgetType").value("oldLineChart"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/old-line-chart.sql")
@Test
void getOldLineChartWithTimeLineWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("old line chart"))
.andExpect(jsonPath("$.widgetType").value("oldLineChart"))
.andExpect(jsonPath("$.content.result.*.values.statistics$defects$automation_bug$ab001").value("1.0"))
.andExpect(jsonPath("$.content.result.*.values.statistics$defects$product_bug$pb001").value("1.0"))
.andExpect(jsonPath("$.content.result.*.values.statistics$defects$automation_bug$ab001").value("1.0"))
.andExpect(jsonPath("$.content.result.*.values.statistics$executions$failed").value("3.0"))
.andExpect(jsonPath("$.content.result.*.values.statistics$executions$passed").value("2.0"))
.andExpect(jsonPath("$.content.result.*.values.statistics$executions$total").value("5.0"));
}
@Sql("/db/widget/old-line-chart.sql")
@Test
void getEmptyContentOldLineChartWithTimeLineWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("old line chart"))
.andExpect(jsonPath("$.widgetType").value("oldLineChart"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/old-line-chart.sql")
@Test
void getOldLineChartWidgetWithIncorrectTimeLine() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/7").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("old line chart"))
.andExpect(jsonPath("$.widgetType").value("oldLineChart"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/investigated-trend.sql")
@Test
void getInvestigatedTrendWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("investigated trend"))
.andExpect(jsonPath("$.widgetType").value("investigatedTrend"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].number").value("1"))
.andExpect(jsonPath("$.content.result[0].values.toInvestigate").value("33.33"))
.andExpect(jsonPath("$.content.result[0].values.investigated").value("66.67"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].number").value("2"))
.andExpect(jsonPath("$.content.result[1].values.toInvestigate").value("66.67"))
.andExpect(jsonPath("$.content.result[1].values.investigated").value("33.33"));
}
//Waiting for fix
@Disabled
@Sql("/db/widget/investigated-trend.sql")
@Test
void getInvestigatedTrendWidgetWithTimeline() throws Exception {
MvcResult mvcResult = mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("investigated trend"))
.andExpect(jsonPath("$.widgetType").value("investigatedTrend"))
.andReturn();
WidgetResource response = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), new TypeReference<WidgetResource>() {
});
System.out.println();
}
@Sql("/db/widget/unique-bug-table.sql")
@Test
void getUniqueBugTableWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("unique bug table"))
.andExpect(jsonPath("$.widgetType").value("uniqueBugTable"))
.andExpect(jsonPath("$.content.result.ticket1[0].itemId").value(2))
.andExpect(jsonPath("$.content.result.ticket1[0].submitter").value("superadmin"))
.andExpect(jsonPath("$.content.result.ticket1[0].itemName").value("test item 2"))
.andExpect(jsonPath("$.content.result.ticket1[0].url").value("http:/example.com/ticket1"))
.andExpect(jsonPath("$.content.result.ticket1[0].launchId").value(1));
}
@Sql("/db/widget/unique-bug-table.sql")
@Test
void getEmptyContentUniqueBugTableWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("unique bug table"))
.andExpect(jsonPath("$.widgetType").value("uniqueBugTable"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/most-time-consuming.sql")
@Test
void getMostTimeConsumingWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("most time consuming"))
.andExpect(jsonPath("$.widgetType").value("mostTimeConsuming"))
.andExpect(jsonPath("$.content.result[0].name").value("test item 3"))
.andExpect(jsonPath("$.content.result[0].duration").value("337.0"))
.andExpect(jsonPath("$.content.result[1].name").value("test item 5"))
.andExpect(jsonPath("$.content.result[1].duration").value("251.0"))
.andExpect(jsonPath("$.content.result[2].name").value("test item 2"))
.andExpect(jsonPath("$.content.result[2].duration").value("192.0"))
.andExpect(jsonPath("$.content.result[3].name").value("test item 1"))
.andExpect(jsonPath("$.content.result[3].duration").value("165.0"))
.andExpect(jsonPath("$.content.result[4].name").value("test item 4"))
.andExpect(jsonPath("$.content.result[4].duration").value("87.0"));
}
@Sql("/db/widget/most-time-consuming.sql")
@Test
void getEmptyContentMostTimeConsumingWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("most time consuming"))
.andExpect(jsonPath("$.widgetType").value("mostTimeConsuming"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/most-time-consuming.sql")
@Test
void getMostTimeConsumingWidgetWithNotExistLaunch() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isNotFound());
}
@Sql("/db/widget/most-time-consuming.sql")
@Test
void getMostTimeConsumingWidgetWithIncludeMethods() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/6").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("most time consuming"))
.andExpect(jsonPath("$.widgetType").value("mostTimeConsuming"))
.andExpect(jsonPath("$.content.result[0].name").value("test item 3"))
.andExpect(jsonPath("$.content.result[0].duration").value("337.0"))
.andExpect(jsonPath("$.content.result[1].name").value("test item 5"))
.andExpect(jsonPath("$.content.result[1].duration").value("251.0"))
.andExpect(jsonPath("$.content.result[2].name").value("test item 2"))
.andExpect(jsonPath("$.content.result[2].duration").value("192.0"))
.andExpect(jsonPath("$.content.result[3].name").value("test item 1"))
.andExpect(jsonPath("$.content.result[3].duration").value("165.0"))
.andExpect(jsonPath("$.content.result[4].name").value("test item 4"))
.andExpect(jsonPath("$.content.result[4].duration").value("87.0"));
}
@Sql("/db/widget/overall-statistics.sql")
@Test
void getOverallStatisticsWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("overall statistics"))
.andExpect(jsonPath("$.widgetType").value("overallStatistics"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$automation_bug$ab001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$product_bug$pb001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$defects$to_investigate$ti001").value("1"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$failed").value("3"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$passed").value("2"))
.andExpect(jsonPath("$.content.result[0].values.statistics$executions$total").value("5"));
}
@Sql("/db/widget/overall-statistics.sql")
@Test
void getEmptyContentOverallStatisticsWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("overall statistics"))
.andExpect(jsonPath("$.widgetType").value("overallStatistics")).andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/activity-stream.sql")
@Test
void getActivityStreamWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/1").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("activity stream"))
.andExpect(jsonPath("$.widgetType").value("activityStream"))
.andExpect(jsonPath("$.content.result[0].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[0].actionType").value("startLaunch"))
.andExpect(jsonPath("$.content.result[0].objectType").value("LAUNCH"))
.andExpect(jsonPath("$.content.result[1].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[1].actionType").value("updateItem"))
.andExpect(jsonPath("$.content.result[1].objectType").value("ITEM"))
.andExpect(jsonPath("$.content.result[2].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[2].actionType").value("deleteLaunch"))
.andExpect(jsonPath("$.content.result[2].objectType").value("LAUNCH"));
}
@Sql("/db/widget/activity-stream.sql")
@Test
void getEmptyContentActivityStreamWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/2").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("activity stream"))
.andExpect(jsonPath("$.widgetType").value("activityStream"))
.andExpect(jsonPath("$.content").isEmpty());
}
@Sql("/db/widget/activity-stream.sql")
@Test
void getActivityStreamWidgetWithNotExistUser() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/3").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isNotFound());
}
@Sql("/db/widget/activity-stream.sql")
@Test
void getActivityStreamWidgetWithEmptyUserOption() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("activity stream"))
.andExpect(jsonPath("$.widgetType").value("activityStream"))
.andExpect(jsonPath("$.content.result[0].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[0].actionType").value("startLaunch"))
.andExpect(jsonPath("$.content.result[0].objectType").value("LAUNCH"))
.andExpect(jsonPath("$.content.result[1].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[1].actionType").value("updateItem"))
.andExpect(jsonPath("$.content.result[1].objectType").value("ITEM"))
.andExpect(jsonPath("$.content.result[2].user").value("superadmin"))
.andExpect(jsonPath("$.content.result[2].actionType").value("deleteLaunch"))
.andExpect(jsonPath("$.content.result[2].objectType").value("LAUNCH"));
}
@Sql("/db/widget/product-status.sql")
@Test
void getProductStatusGroupedByLaunchWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/4").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("product status"))
.andExpect(jsonPath("$.widgetType").value("productStatus"))
.andExpect(jsonPath("$.content.result[0].name").value("test launch"))
.andExpect(jsonPath("$.content.result[0].number").value("1"))
.andExpect(jsonPath("$.content.result[0].attributes").isNotEmpty())
.andExpect(jsonPath("$.content.result[0].passingRate").value("40.0"))
.andExpect(jsonPath("$.content.result[1].name").value("test launch"))
.andExpect(jsonPath("$.content.result[1].number").value("2"))
.andExpect(jsonPath("$.content.result[1].attributes").doesNotExist())
.andExpect(jsonPath("$.content.result[1].passingRate").value("20.0"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$executions$passed").value("3"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$executions$skipped").value("1"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$defects$to_investigate$ti001").value("3"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$defects$product_bug$pb001").value("2"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$defects$automation_bug$ab001").value("1"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$executions$failed").value("6"))
.andExpect(jsonPath("$.content.result[2].sum.statistics$executions$total").value("10"))
.andExpect(jsonPath("$.content.result[2].averagePassingRate").value("30.0"));
}
@Sql("/db/widget/product-status.sql")
@Test
void getEmptyContentProductStatusGroupedByLaunchWidget() throws Exception {
mockMvc.perform(get(SUPERADMIN_PROJECT_BASE_URL + "/widget/5").with(token(oAuthHelper.getSuperadminToken())))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("product status"))
.andExpect(jsonPath("$.widgetType").value("productStatus"))
.andExpect(jsonPath("$.content").isEmpty());
}
} | Flaky widget junit test update
| src/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerTest.java | Flaky widget junit test update | <ide><path>rc/test/java/com/epam/ta/reportportal/ws/controller/WidgetControllerTest.java
<ide> .andExpect(jsonPath("$.widgetType").value("flakyTestCases"))
<ide> .andExpect(jsonPath("$.content.latestLaunch.name").value("test launch"))
<ide> .andExpect(jsonPath("$.content.flaky[0].flakyCount").value("1"))
<del> .andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4"))
<del> .andExpect(jsonPath("$.content.flaky[1].flakyCount").value("0"))
<del> .andExpect(jsonPath("$.content.flaky[1].itemName").value("test item 1"))
<del> .andExpect(jsonPath("$.content.flaky[2].flakyCount").value("0"))
<del> .andExpect(jsonPath("$.content.flaky[2].itemName").value("test item 2"))
<del> .andExpect(jsonPath("$.content.flaky[3].flakyCount").value("0"))
<del> .andExpect(jsonPath("$.content.flaky[3].itemName").value("test item 3"))
<del> .andExpect(jsonPath("$.content.flaky[4].flakyCount").value("0"))
<del> .andExpect(jsonPath("$.content.flaky[4].itemName").value("test item 5"));
<add> .andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4"));
<ide> }
<ide>
<ide> @Sql("/db/widget/flaky-test-cases.sql")
<ide> .andExpect(jsonPath("$.widgetType").value("flakyTestCases"))
<ide> .andExpect(jsonPath("$.content.latestLaunch.name").value("test launch"))
<ide> .andExpect(jsonPath("$.content.flaky[0].flakyCount").value("1"))
<del> .andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4"))
<del> .andExpect(jsonPath("$.content.flaky[1].flakyCount").value("0"))
<del> .andExpect(jsonPath("$.content.flaky[1].itemName").value("test item 1"))
<del> .andExpect(jsonPath("$.content.flaky[2].flakyCount").value("0"))
<del> .andExpect(jsonPath("$.content.flaky[2].itemName").value("test item 2"))
<del> .andExpect(jsonPath("$.content.flaky[3].flakyCount").value("0"))
<del> .andExpect(jsonPath("$.content.flaky[3].itemName").value("test item 3"))
<del> .andExpect(jsonPath("$.content.flaky[4].flakyCount").value("0"))
<del> .andExpect(jsonPath("$.content.flaky[4].itemName").value("test item 5"));
<add> .andExpect(jsonPath("$.content.flaky[0].itemName").value("test item 4"));
<ide> }
<ide>
<ide> @Sql("/db/widget/cases-trend.sql") |
|
JavaScript | mit | e2fa9f52e72f549911fa722fb37bc218301e4240 | 0 | MyChannel-Apps/KFramework,MyChannel-Apps/KFramework | var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}
if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}
if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}
function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}
function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}
function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}
function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}
var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}
var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}
var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}()); | KFramework/framework/KFramework.min.js | var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}
if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}
if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}
function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}
function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}
function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}
function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}
var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}
var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}
var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
if(callback.apply(this[index],index)===false){break;}}}});}
if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
if(order===undefined){order=='ASC';}
var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
keys.push({index:index,value:this[index],sortby:sortBy});}
if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
for(var key in newObj){this[key]=newObj[key];}
return newObj;}});}
if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
index++;}
string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
string+=prepareLink(_text);}
if(_command_left!=undefined){string+='|'+_command_left;}
if(_command_right!=undefined){string+='|'+_command_right;}
string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
output+='.'+name+(value==0x01?'':'_'+value);}}
return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
_text=text;if(command===undefined){return;}
_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
if(_command.length>0){string+='call|'+_command;}
for(var name in _properties){string+='|'+name+'|'+_properties[name];}
string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
output+='}<°';for(var index in _rows){output+=_rows[index];}
output+='°>{endtable}<°';return output;};}
function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
return output;};KRow();}
function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
if(_style&FontStyle.ITALIC){output+='"';}
output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
output+=_size+'°';return output;};KFont(name,style,size);}var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
if(value===undefined){value=_defaults[key];}
if(!(error=this.check(key,value))){return error;}
if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
if(x.length==1){x.push(x[0]);}
x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
return'';}
function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
output+='\n'+line;});return output;}
this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
if(filter.age!=undefined){}
if(filter.nickname!=undefined){}
if(filter.minutes!=undefined){}
if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
this.create(uid);if(kn<=0.00){return false;}
if(_data[uid].knuddel<kn){return false;}
_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
if(kn===undefined){return false;}
if(kn<0){return false;}
if(kn>_data[uid].knuddel){return false;}
this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
if(kn===undefined){return;}
if(kn<0){return false;}
this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
if(_data[uid].buyin!=0.00){return;}
if(_data[uid].payout!=0.00){return;}
delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
if(data===undefined){Logger.error('No Data submitted');return false;}
selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
this.public=function(message){if(message instanceof KCode){message=message.toString();}
_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
if(_debug){string=string.replace(/°/g,'\\°');}
if(_minify){string=string.replace(/°°/g,'');}
return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
return nickname;};}()); | Build/Minify Framework (1.0.3 - 05.01.2015 - 09:18:43)
| KFramework/framework/KFramework.min.js | Build/Minify Framework (1.0.3 - 05.01.2015 - 09:18:43) | <ide><path>Framework/framework/KFramework.min.js
<ide> var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
<add>if(callback.apply(this[index],index)===false){break;}}}});}
<add>if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
<add>if(order===undefined){order=='ASC';}
<add>var keys=[];for(var index in this){var sortby=0;if(byKey=='index'){sortby=index;}else if(byKey=='value'){sortby=this[index];}else if(this[index].hasOwnProperty(byKey)){sortby=this[index][byKey];}
<add>keys.push({index:index,value:this[index],sortby:sortBy});}
<add>if(order=='ASC'){keys.sort(function(a,b){return a.sortby-b.sortby;});}else{keys.sort(function(a,b){return b.sortby-a.sortby;});}
<add>var newObj={};for(var k in keys){newObj[keys[k].index]=this[keys[k].index];delete this[keys[k].index];}
<add>for(var key in newObj){this[key]=newObj[key];}
<add>return newObj;}});}
<add>if(!Object.prototype.exists){Object.defineProperty(Object.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this[value]!=undefined);}});}
<add>if(!Object.prototype.compare){Object.defineProperty(Object.prototype,'compare',{enumerable:false,configurable:false,writable:false,value:function(defaultObj){for(var property in defaultObj){if(this[property]&&(typeof(this[property])=='object')&&(this[property].toString()=='[object Object]')&&defaultObj[property]){this[property].compare(defaultObj[property]);}else if(typeof this[property]=='undefined'){this[property]=defaultObj[property];}}
<add>return this;}});}if(!String.prototype.startsWith){Object.defineProperty(String.prototype,'startsWith',{enumerable:false,configurable:false,writable:false,value:function(searchString,position){position=position||0;return this.lastIndexOf(searchString,position)===position;}});}
<add>if(!String.prototype.endsWith){Object.defineProperty(String.prototype,'endsWith',{value:function(searchString,position){var subjectString=this.toString();if(position===undefined||position>subjectString.length){position=subjectString.length;}
<add>position-=searchString.length;var lastIndex=subjectString.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position;}});}
<add>if(!String.prototype.format){Object.defineProperty(String.prototype,'format',{enumerable:false,configurable:false,writable:false,value:function(){var args=arguments;return this.replace(/{(\d+)}/g,function(match,number){return(typeof(args[number])!='undefined')?args[number]:match;});}});}
<add>if(!String.prototype.contains){Object.defineProperty(String.prototype,'contains',{enumerable:false,configurable:false,writable:false,value:function(args){if(typeof(args)=='string'){args=[args];}
<add>for(var x in args){if(this.indexOf(args[x])>-1){return true;}}
<add>return false;}});}if(!Array.prototype.each){Object.defineProperty(Array.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index=0;index<this.length;index++){if(callback.apply(this[index],index)===false){break;}}}});}
<add>if(!Array.prototype.random){Object.defineProperty(Array.prototype,'random',{enumerable:false,configurable:false,writable:false,value:function(){return this[RandomOperations.nextInt(this.length)];}});}
<add>if(!Array.prototype.exists){Object.defineProperty(Array.prototype,'exists',{enumerable:false,configurable:false,writable:false,value:function(value){return(this.indexOf(value)>-1);}});}function KCountdown(){var _properties={};this.setTime=function(time){_properties.time=time;};this.setFormat=function(format){_properties.format=format;};this.setText=function(text){_properties.timeUpText=text;};this.toString=function(){var string='°>{countdown}';var index=0;for(var name in _properties){string+=name+'='+_properties[name];if(index+1<Object.keys(_properties).length){string+='|';}
<add>index++;}
<add>string+='<°';return string;};}function KLink(text){var _text='';var _command_left=undefined;var _command_right=undefined;var _hover=true;function KLink(text){_text=text||'';}
<add>function prepareLink(string){return string.replace(/(<|>|\||°)/g,'\\$1');}
<add>this.setCommand=function(command_left,command_right){_command_left=command_left;_command_right=command_right;};this.enableHover=function(state){_hover=state;};this.toString=function(){var string='°>';if(_text instanceof KImage){string+=_text.toString(true);string+='|'+_text.toString(true)+'<>--<>';}else{if(_hover==false){string+='_h';}
<add>string+=prepareLink(_text);}
<add>if(_command_left!=undefined){string+='|'+_command_left;}
<add>if(_command_right!=undefined){string+='|'+_command_right;}
<add>string+='<°';return string;};KLink(text);};function KImage(image){var _path='';var _name='';var _extension='';var _properties={};function KImage(image){var split=image.split('.');_name=split[0];_extension=split[1];var first=_name.substring(0,1);if(first=='/'||first=='~'){_name=_name.substring(1);_path=KnuddelsServer.getFullImagePath('');}}
<add>this.setContainerSize=function(width,height){_properties.w=width;_properties.h=height;};this.setSize=function(width,height){_properties.mw=width;_properties.mh=height;};this.setPosition=function(x,y){_properties.mx=x;_properties.my=y;};this.setLabel=function(text){_properties.label=text;};this.setLabelPosition=function(x,y){_properties.lmx=x;_properties.lmy=y;};this.setLabelColor=function(color){_properties.labelcolor=color;};this.enableLabelBorder=function(bool){_properties.labelborder=(bool==true?'1':'0');};this.setBorder=function(size){_properties.border=size;};this.setQuadcut=function(size){_properties.quadcut=size;};this.setShadow=function(position){_properties.shadow=position;};this.setMirror=function(state){_properties.mirror=(state==true?0x01:0x00);};this.setGreyscale=function(state){_properties.gray=(state==true?0x01:0x00);};this.toString=function(only_path){only_path=only_path||false;var output=(only_path==true?'':'°>')+_path+_name;if(Object.keys(_properties).length>0){output+='..';for(var name in _properties){var value=_properties[name];if(value==0x00){continue;}
<add>output+='.'+name+(value==0x01?'':'_'+value);}}
<add>return output+'.'+_extension+(only_path==true?'':'<°');};KImage(image);}function KButton(text,command){var _text='';var _command='';var _properties={};function KButton(text,command){if(text===undefined){return;}
<add>_text=text;if(command===undefined){return;}
<add>_command=command;};this.getCommand=function(){return _command;};this.setCommand=function(command){_command=command;};this.getText=function(){return _text;};this.setText=function(text){_text=text;};this.setIcon=function(icon){if(icon.indexOf('https://')==0||icon.indexOf('http://')==0){Logger.info("Can\t use http:// or https:// URL\'s on Buttons because the Path is implemented on the Client side!");}
<add>_properties.icon=icon;};this.removeIcon=function(){delete _properties.icon;};this.setColor=function(color){_properties.color=color;};this.removeColor=function(){delete _properties.color;};this.getHeight=function(){return _properties.height;};this.setHeight=function(height){_properties.height=height;};this.removeHeight=function(){delete _properties.height;};this.getWidth=function(){return _properties.width;};this.setWidth=function(width){_properties.width=width;};this.removeWidth=function(){delete _properties.width;};this.setSize=function(width,height){this.setWidth(width);this.setHeight(height);};this.removeSize=function(){this.removeWidth();this.removeHeight();};this.getX=function(){return _properties.mx;};this.setX=function(x){_properties.mx=x;};this.getY=function(){return _properties.my;};this.setY=function(y){_properties.my=y;};this.setPosition=function(x,y){this.setX(x);this.setY(y);};this.useTextborder=function(bool){if(bool){_properties.textborder='1';}else{delete _properties.textborder;}};this.setEnabled=function(bool){if(bool==false){_properties.enabled='0';}else{delete _properties.enabled;}};this.toString=function(){var string='°>{button}';if(_text.length>0){string+=_text+'||';}
<add>if(_command.length>0){string+='call|'+_command;}
<add>for(var name in _properties){string+='|'+name+'|'+_properties[name];}
<add>string+='<°';return string;};KButton(text,command);}function KTable(){var _rows=[];this.add=function(element){_rows.push(element);};this.toString=function(){var output='°>{table';for(var index in _rows){var cel=_rows[index].getCells();output+='|'+cell.getSize();}
<add>output+='}<°';for(var index in _rows){output+=_rows[index];}
<add>output+='°>{endtable}<°';return output;};}
<add>function KRow(){var _cells=[];function KRow(){_cells=arguments||[];}
<add>this.getCells=function(){return _cells;};this.toString=function(){var output='°>{tr}<°';for(var index in _cells){output+=_cells[index];}
<add>return output;};KRow();}
<add>function KCell(size,content){var _size=0;var _content='';function KCell(size,content){_size=size;_content=content;}
<add>this.toString=function(){return'°>{tc}<°'+_content;};KCell(size,content);}var FontStyle={PLAIN:0x00,BOLD:0x01,ITALIC:0x02};function KFont(name,style,size){var _name='Arial';var _size=14;var _style=FontStyle.PLAIN;var _available=['RobotoBold','RobotoLight','FinelinerScript','Arial','Impact'];function KFont(name,style,size){_name=name;_size=size;_style=style;}
<add>this.toString=function(){var output='';if(_style&FontStyle.BOLD){output+='_';}
<add>if(_style&FontStyle.ITALIC){output+='"';}
<add>output+='°';if(_available.indexOf(_name)>-1){output+='>{font}'+_name+'<';}else{Logger.info('Font '+_name+' does\'nt exists!');}
<add>output+=_size+'°';return output;};KFont(name,style,size);}var VERSION='1.0.3';var Status={Newbie:0,Family:1,Stammi:2,Ehrenz:3,Admin:6,Sysadmin:11,Bot:-1};var Alignment={LEFT:'°>LEFT<°',MIDDLE:'°>CENTER<°',CENTER:'°>CENTER<°',RIGHT:'°>RIGHT<°',JUSTIFY:'°>JUSTIFY<°',};if(!Object.prototype.each){Object.defineProperty(Object.prototype,'each',{enumerable:false,configurable:false,writable:false,value:function(callback){for(var index in this){if(this.hasOwnProperty(index)){continue;}
<ide> if(callback.apply(this[index],index)===false){break;}}}});}
<ide> if(!Object.prototype.sort){Object.defineProperty(Object.prototype,'sort',{enumerable:false,configurable:false,writable:false,value:function(byKey,order){if(byKey===undefined){byKey=='index';}
<ide> if(order===undefined){order=='ASC';}
<ide> return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
<ide> if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
<ide> if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
<add>return nickname;};}());var KConfig=(new function(){var _data=DB.load('_config');var _defaults={};var _puffer={};var _useChangesPuffer=false;this.setDefaults=function(defaults){_defaults=defaults;_data.compare(_defaults);};this.saveData=function(){DB.save('_config',_data);};this.resetData=function(){DB.save('_config',{});_data={};};this.applyChanges=function(){_useChangesPuffer=true;_puffer.each(function(newvalue,key){_data[key]=newvalue;});_puffer={};};this.get=function(key){if(key===undefined){Logger.error('No key submitted');return undefined;}
<add>if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return undefined;}
<add>return _data[key];};this.set=function(key,value){if(key===undefined){Logger.error('No key submitted');return false;}
<add>if(_data[key]===undefined){Logger.error('Key "'+key+'" not exists');return false;}
<add>if(value===undefined){value=_defaults[key];}
<add>if(!(error=this.check(key,value))){return error;}
<add>if(_useChangesPuffer){_puffer[key]=value;}else{_data[key]=value;}};this.check=function(){return true;};}());var Cron=(new function(){var _cronjobs=[];var _watcher;var _offlineCheck=false;this.init=function(){if(_watcher!=undefined){clearInterval(_watcher);}
<add>_watcher=setInterval(this.run,500);};this.enableOfflineRunCheck=function(){_offlineCheck=true;};this.checkOfflineRun=function(job){if(job.getLastCheck()==0){return;}
<add>while(new Date().getTime()>=job.getLastCheck()){var time=new Date(job.getLastCheck()+500);job.setLastCheck(time);if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);return;}}}}}}}};this.run=function(){var time=new Date();for(var index in _cronjobs){var job=_cronjobs[index];if(!job.isRunning()){continue;}
<add>if(time.getTime()-job.getLastRun()>60000){if(Cron.match(job.getMinutes(),time.getMinutes())){if(Cron.match(job.getHours(),time.getHours())){if(Cron.match(job.getDate(),time.getDate())){if(Cron.match(job.getMonth(),time.getMonth())){if(Cron.match(job.getDay(),time.getDay())){job.run(time);}}}}}}}};this.add=function(cronjob){_cronjobs.push(cronjob);if(_offlineCheck){this.checkOfflineRun(cronjob);}};this.match=function(a,b){for(var index=0;index<a.length;index++){var c=a[index];if(c[0]===-1||(b>=c[0]&&b<=c[1])){var b0=b-c[0];if(c[2]===-1||b===0||b%c[2]===0){return true;}}}
<add>return false;};this.parse=function(entry){return entry.split(',').map(function(index){var z=index.split('/');var x=z[0].split('-');if(x[0]=='*'){x[0]=-1;}
<add>if(x.length==1){x.push(x[0]);}
<add>x[2]=z.length===1?-1:z[1];x[0]=parseInt(x[0]);x[1]=parseInt(x[1]);x[2]=parseInt(x[2]);return x;});};this.onShutdown=function(){for(var index in _cronjobs){_cronjobs[index].onShutdown();}
<add>if(_watcher!=undefined){clearInterval(_watcher);}};this.init();}());function Cronjob(name,cycle,callback){var _name='';var _cycle='* * * * *';var _cycle_data=[];var _is_running=false;var _callback=function(time){};var _last_run=undefined;var _last_check=undefined;var _time_data={minute:'*',hour:'*',date:'*',month:'*',day:'*'};function Cronjob(instance,name,cycle,callback){_name=name;_cycle=cycle;_callback=callback;_cycle_data=_cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);_crondb=DB.load('_cron_'+_name,{run:0,check:0});_last_run=new Date(parseInt(_crondb.run));_last_check=new Date(parseInt(_crondb.check));_time_data={minute:Cron.parse(_cycle_data[1]),hour:Cron.parse(_cycle_data[2]),date:Cron.parse(_cycle_data[3]),month:Cron.parse(_cycle_data[4]),day:Cron.parse(_cycle_data[5])};Cron.add(instance);instance.start();}
<add>this.getLastRun=function(){return _last_run.getTime();};this.getName=function(){return _name;};this.getLastCheck=function(){return _last_check.getTime();};this.setLastCheck=function(time){_last_check=time;};this.isRunning=function(){return _is_running;};this.start=function(){_is_running=true;};this.stop=function(){_is_running=false;};this.run=function(time){_last_check=time;_last_run=time;_callback(time);};this.getMinutes=function(){return _time_data.minute;};this.getHours=function(){return _time_data.hour;};this.getDate=function(){return _time_data.date;};this.getMonth=function(){return _time_data.month;};this.getDay=function(){return _time_data.day;};this.onShutdown=function(){this.stop();DB.save('_cron_'+_name,{run:_last_run.getTime(),check:_last_check.getTime()});};Cronjob(this,name,cycle,callback);}var Logger=(new function(){var _logger;function Logger(){_logger=KnuddelsServer.getDefaultLogger();};function getStrackTrace(){try{null.toString();}catch(e){return prettyStackTrace(e.stack);}
<add>return'';}
<add>function prettyStackTrace(stack){var lines=stack.replace(/\t/g,' ').replace(/\(anonymous\)/g,'').replace(/at (.*)@(.*): /g,'at ').split('\n');var output='';lines.each(function(line,index){if(index<=1){return;}
<add>output+='\n'+line;});return output;}
<add>this.debug=function(message){_logger.debug(message+getStrackTrace());};this.info=function(message){_logger.info(message+getStrackTrace());};this.error=function(message){_logger.error(message+getStrackTrace());};this.fatal=function(message){_logger.fatal(message+getStrackTrace());};this.warn=function(message){_logger.warn(message+getStrackTrace());};Logger();}());var Channel=(new function(){var _channel=KnuddelsServer.getChannel();var _configuration=_channel.getChannelConfiguration();var _rights=_configuration.getChannelRights();this.getName=function(){return _channel.getChannelName();};this.getModerators=function(){return _rights.getChannelModerators();};this.getOwners=function(){return _rights.getChannelOwners();};this.getMods=function(){return _rights.getEventModerators();};this.getUsers=function(filter){filter=filter||{};var types=[UserType.Human];if(filter.bot!=undefined){if(filter.bot==true){types.push(UserType.AppBot);types.push(UserType.SystemBot);}}
<add>var users=[];var _users=_channel.getOnlineUsers(types);if(!filter.exists('online')&&!filter.exists('inChannel')&&!filter.exists('away')&&!filter.exists('developer')&&!filter.exists('owner')&&!filter.exists('event')&&!filter.exists('cm')&&!filter.exists('status')&&!filter.exists('gender')&&!filter.exists('age')&&!filter.exists('nickname')&&!filter.exists('minutes')&&!filter.exists('readme')){return _users;}
<add>_users.each(function(user,index){if(filter.online!=undefined&&filter.online==true&&user.isOnline()==true){users.push(user);}
<add>if(filter.inChannel!=undefined&&filter.inChannel==true&&user.isOnlineInChannel()==true){users.push(user);}
<add>if(filter.away!=undefined&&filter.away==true&&user.isAway()==true){users.push(user);}
<add>if(filter.developer!=undefined&&filter.developer==true&&user.isAppDeveloper()==true){users.push(user);}
<add>if(filter.owner!=undefined&&filter.owner==true&&user.isChannelOwner()==true){users.push(user);}
<add>if(filter.event!=undefined&&filter.event==true&&user.isEventModerator()==true){users.push(user);}
<add>if(filter.cm!=undefined&&filter.cm==true&&user.isChannelModerator()==true){users.push(user);}
<add>if(filter.status!=undefined&&filter.status.exists(user.getUserStatus())){users.push(user);}
<add>if(filter.gender!=undefined&&filter.gender.exists(user.getGender())){users.push(user);}
<add>if(filter.age!=undefined){}
<add>if(filter.nickname!=undefined){}
<add>if(filter.minutes!=undefined){}
<add>if(filter.readme!=undefined){}});return users;};}());var KBank=(new function(){var _data=DB.load('_bank');this.create=function(uid){if(uid===undefined){return;}
<add>if(_data[uid]===undefined){_data[uid]={knuddel:0.00,buyin:0.00,payout:0.00,};}};this.getKn=function(uid){if(uid===undefined){return;}
<add>this.create(uid);return _data[uid].knuddel;};this.getKonto=function(uid){if(uid===undefined){return;}
<add>this.create(uid);return _data[uid];};this.setKn=function(uid,kn){if(uid===undefined){return;}
<add>if(kn===undefined){return;}
<add>this.create(uid);if(kn<=0.00){return false;}
<add>_data[uid].knuddel=kn;};this.addKn=function(uid,kn){if(uid===undefined){return;}
<add>if(kn===undefined){return;}
<add>this.create(uid);_data[uid].knuddel+=kn;};this.delKn=function(uid,kn){if(uid===undefined){return;}
<add>if(kn===undefined){return;}
<add>this.create(uid);if(kn<=0.00){return false;}
<add>if(_data[uid].knuddel<kn){return false;}
<add>_data[uid].knuddel-=kn;return true;};this.payout=function(uid,kn,reason){if(uid===undefined){return false;}
<add>if(kn===undefined){return false;}
<add>if(kn<0){return false;}
<add>if(kn>_data[uid].knuddel){return false;}
<add>this.create(uid);_data[uid].knuddel-=kn;_data[uid].payout+=kn;Bot.knuddel(KnuddelsServer.getUser(uid),kn,reason);return true;};this.payin=function(uid,kn){if(uid===undefined){return;}
<add>if(kn===undefined){return;}
<add>if(kn<0){return false;}
<add>this.create(uid);_data[uid].knuddel+=kn;_data[uid].buyin+=kn;};this.saveData=function(){this.cleanData();DB.save('_bank',_data);};this.resetData=function(){DB.save('_bank',{});_data={};};this.fixData=function(){_data.each(function(uid){_data[uid].knuddel=parseFloat(_data[uid].knuddel);_data[uid].buyin=parseFloat(_data[uid].buyin);_data[uid].payout=parseFloat(_data[uid].payout);});};this.cleanData=function(){_data.each(function(uid){if(_data[uid].knuddel!=0.00){return;}
<add>if(_data[uid].buyin!=0.00){return;}
<add>if(_data[uid].payout!=0.00){return;}
<add>delete _data[uid];});};this.getUsers=function(){return Object.keys(_data);};this.getTransit=function(){transit=0.00;_data.each(function(uid){transit+=KBank.getKn(uid);});return transit;};this.fixData();}());var DB=(new function(){this.getUser=function(user){Logger.info('DB.getUser(user) is DEPRECATED');return user.getPersistence();};this.getChannel=function(){Logger.info('DB.getChannel() is DEPRECATED');return KnuddelsServer.getPersistence();};this.load=function(key,defaultValue,user){if(key===undefined){Logger.error('No key submitted');return false;}
<add>selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
<add>switch(typeof defaultValue){case'string':return selectedDB.getString(key,defaultValue);break;case'number':return selectedDB.getNumber(key,defaultValue);break;case'object':return selectedDB.getObject(key,defaultValue);break;case'undefined':return selectedDB.getObject(key,{});break;}
<add>return false;};this.save=function(key,data,user){if(key===undefined){Logger.error('No key submitted');return false;}
<add>if(data===undefined){Logger.error('No Data submitted');return false;}
<add>selectedDB=KnuddelsServer.getPersistence();if(user!=undefined){selectedDB=user.getPersistence();}
<add>switch(typeof data){case'string':selectedDB.setString(key,data);break;case'number':selectedDB.setNumber(key,data);break;case'object':selectedDB.setObject(key,data);break;}
<add>return true;};}());var Bot=(new function(){var _user=KnuddelsServer.getDefaultBotUser();this.getNick=function(){return _user.getNick();};this.join=function(){_user.joinChannel();};this.leave=function(){_user.leaveChannel();};this.knuddel=function(user,amount,message){if(message===undefined){_user.transferKnuddel(user,amount);}else{_user.transferKnuddel(user,amount,message);}};this.getKnuddels=function(){return _user.getKnuddelAmount().asNumber();};this.exception=function(exception){_user.sendPublicMessage('°RR°_Exception:_°r°#'+(exception.message==undefined?exception:exception.message));};this.publicMessage=function(message){Logger.info('Bot.publicMessage(message) is DEPRECATED');this.public(message);}
<add>this.postMessage=function(user,message,topic){Logger.info('Bot.postMessage(user, message, topic) is DEPRECATED');this.post(user,message,topic);}
<add>this.privateMessage=function(user,message){Logger.info('Bot.privateMessage(user, message) is DEPRECATED');this.private(user,message);}
<add>this.public=function(message){if(message instanceof KCode){message=message.toString();}
<add>_user.sendPublicMessage(message);};this.post=function(nick,message,topic){if(message instanceof KCode){message=message.toString();}
<add>if(nick==undefined){Channel.getUsers().each(function(user){user.sendPostMessage(topic,message);});}else{nick.sendPostMessage(topic,message);}};this.private=function(nick,message){if(message instanceof KCode){message=message.toString();}
<add>if(nick==undefined){Channel.getUsers().each(function(user){user.sendPrivateMessage(message);});}else{nick.sendPrivateMessage(message);}};this.exec=function(command){_user.sendToChannel(command);};}());function KCode(){var _buffer=[];var _debug=false;var _minify=true;this.append=function(component){_buffer.push(component);};this.newLine=function(){_buffer.push('°#°');_buffer.push('#');};this.setAlignment=function(alignment){_buffer.push(alignment);};this.addImage=function(file){_buffer.push('°>'+KnuddelsServer.getFullImagePath(file)+'<°');};this.toString=function(){var string='';for(var index in _buffer){var component=_buffer[index];if(component instanceof String){string+=component;}else{string+=component.toString();}}
<add>if(_debug){string=string.replace(/°/g,'\\°');}
<add>if(_minify){string=string.replace(/°°/g,'');}
<add>return string;};};var Users=(new function(){this.get=function(nickname){if(typeof(nickname)=='number'){if(KnuddelsServer.canAccessUser(nickname)){nickname=KnuddelsServer.getUser(nickname);}}
<add>if(KnuddelsServer.userExists(nickname)){var userId=KnuddelsServer.getUserId(nickname);if(KnuddelsServer.canAccessUser(userId)){return KnuddelsServer.getUser(userId);}}else{return undefined;}
<add>if(typeof(nickname)=='string'){return(new function(){var _nickname=nickname;var _uid=userId;this.virtual=true;this.getPersistence=function(_uid){return(new function VirtualPersistence(uid){_uid=uid;this.getString=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getNumber=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.getObject=function(key,defaults){return DB.load('_userdb')[_uid][key]||defaults;};this.deleteNumber=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteObject=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.deleteString=function(key){userdb=DB.load('_userdb');delete userdb[_uid][key];DB.save('_userdb',userdb);};this.setString=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setNumber=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};this.setObject=function(key,data){userdb=DB.load('_userdb');userdb[_uid][key]=data;DB.save('_userdb',userdb);};}());};this.equals=function(user){Logger.warn('using User.equals() on virtual User-Object');};this.getAge=function(){return-1;};this.getGender=function(){return Gender.Unknown;};this.getKnuddelAmount=function(){return new KnuddelAmount(0);};this.getNick=function(){return _nickname;};this.getOnlineMinutes=function(){return-1;};this.getProfileLink=function(){return'°>_h'+_nickname.escapeKCode()+'|/w "|/serverpp "<°';};this.getReadme=function(){return'';};this.getRegDate=function(){return new Date(0);};this.getUserId=function(){return _uid;};this.getUserStatus=function(){return UserStatus.Newbie;};this.getUserType=function(){return UserType.Human;};this.isAppDeveloper=function(){return false;};this.isAway=function(){return false;};this.isChannelModerator=function(){return false;};this.isChannelOwner=function(){return false;};this.isEventModerator=function(){return false;};this.isOnline=function(){return false;};this.isOnlineInChannel=function(){return false;};this.sendPostMessage=function(topic,message){Logger.error('Can\t send message to a virtual User-Object!');};this.sendPrivateMessage=function(message){Logger.error('Can\t send message to a virtual User-Object!');};}());}
<ide> return nickname;};}()); |
|
Java | lgpl-2.1 | e7ab61fb049df91b87e84a4cfc103b425efd14dc | 0 | JasonILTG/Minecraft-Modding | package com.JasonILTG.ScienceMod.tileentity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IChatComponent;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import com.JasonILTG.ScienceMod.init.ScienceModItems;
import com.JasonILTG.ScienceMod.util.NBTHelper;
public class TEElectrolyzer extends TEMachine implements ISidedInventory
{
public static final int INVENTORY_SIZE = 4;
public static final int ITEM_INPUT_INDEX = 0;
public static final int JAR_INPUT_INDEX = 1;
public static final int[] OUTPUT_INDEX = { 2, 3 };
public static final int DEFAULT_MAX_PROGRESS = 100;
private Recipe currentRecipe;
private FluidTank inputTank;
public TEElectrolyzer()
{
// Initialize everything
super(DEFAULT_MAX_PROGRESS);
inventory = new ItemStack[INVENTORY_SIZE];
currentRecipe = null;
inputTank = new FluidTank(10000);
// The inventory slot at jar can only hold jars.
inventory[JAR_INPUT_INDEX] = new ItemStack(ScienceModItems.jar, 0);
}
@Override
public void update()
{
electrolyze();
}
private void electrolyze()
{
ItemStack[] currentOutput = tryElectrolyze(currentRecipe);
if (currentOutput != null)
{
// Continue current recipe.
currentProgress++;
}
// The current recipe is no longer valid. Once we find a new recipe we can reset the current progress and change over to the
// new recipe.
for (Recipe newRecipe : Recipe.values())
{
ItemStack[] attemptOutput = tryElectrolyze(newRecipe);
if (attemptOutput != null)
{
// Found a new recipe.
currentRecipe = newRecipe;
currentProgress = 1; // Account for the progress in the tick
}
}
if (currentProgress >= maxProgress)
{
// Time to output items and reset progress.
currentProgress = 0;
for (int i = 0; i < OUTPUT_INDEX.length; i++) {
inventory[OUTPUT_INDEX[i]].stackSize += currentOutput[i].stackSize;
}
}
}
/**
* Tries to electrolyze the inputs with the given recipe.
*
* @param recipeToUse the recipe to try
* @return
* If the operation is successful, returns the ItemStacks IN THE RIGHT ORDER so that they can be inserted into the output
* slots easily. If the operation is not successful, returns null.
*/
private ItemStack[] tryElectrolyze(Recipe recipeToUse)
{
// null check
if (recipeToUse == null) return null;
// If the recipe cannot use the input, the attempt fails.
if (!recipeToUse.canProcessUsing(inventory[JAR_INPUT_INDEX], inventory[ITEM_INPUT_INDEX], inputTank.getFluid()))
return null;
// Try to match output items with output slots.
ItemStack[] storedOutput = { inventory[OUTPUT_INDEX[0]], inventory[OUTPUT_INDEX[1]] };
ItemStack[] newOutput = recipeToUse.getOutputs();
ItemStack[] outputToAdd = new ItemStack[storedOutput.length];
// Use a copied version of the output inventory to prevent modification of the inventory
ItemStack[] predictedOutput = new ItemStack[storedOutput.length];
System.arraycopy(storedOutput, 0, predictedOutput, 0, storedOutput.length);
for (ItemStack stack : newOutput)
{
// Find out how to insert the stack
ItemStack[] pattern = findInsertPattern(stack, predictedOutput);
// If the return is null, that means we can't insert the stack.
if (pattern == null) return null;
// Add the pattern to the output and to the predicted pattern
outputToAdd = mergeStackArrays(outputToAdd, pattern);
predictedOutput = mergeStackArrays(predictedOutput, pattern);
}
return outputToAdd;
}
private ItemStack[] findInsertPattern(ItemStack stackToInsert, ItemStack[] insertTarget)
{
// null check
if (insertTarget == null) return null;
if (stackToInsert == null) return new ItemStack[insertTarget.length];
// Generate local copies to prevent modification of the parameters
ItemStack stack = stackToInsert.copy();
// insertTarget should not be modified in the method
// Initialize the output array
ItemStack[] insertPattern = new ItemStack[insertTarget.length];
// First pass through the array to look for already existing stacks of the same item
for (int i = 0; i < insertPattern.length; i++)
{
if (insertTarget[i] != null && insertTarget[i].isItemEqual(stackToInsert)
&& insertTarget[i].stackSize < insertTarget[i].getMaxStackSize())
{
// The target slot has a matching ItemStack and can store more
if (insertTarget[i].getMaxStackSize() - insertTarget[i].stackSize > stack.stackSize) {
// The stack has more than enough space
insertPattern[i] = stack;
// Insertion complete, return the pattern
return insertPattern;
}
// The target slot does not have enough space
insertPattern[i] = stack.splitStack(insertTarget[i].getMaxStackSize() - insertTarget[i].stackSize);
}
}
// Second pass through the array to look for any empty output slot
for (int i = 0; i < insertPattern.length; i++)
{
if (insertTarget[i] == null) {
insertPattern[i] = stack;
return insertPattern;
}
}
// If it comes to this, we can't insert output into the output slots.
return null;
}
private static ItemStack[] mergeStackArrays(ItemStack[] stackArray1, ItemStack[] stackArray2)
{
// null and length mismatch check
if (stackArray1 == null || stackArray2 == null || stackArray1.length != stackArray2.length) return null;
// Generate output
ItemStack[] outStack = new ItemStack[stackArray1.length];
for (int i = 0; i < outStack.length; i++) {
// For each ItemStack in the array
if (stackArray1[i] == null) {
outStack[i] = stackArray2[i];
}
else if (stackArray2[i] == null) {
outStack[i] = stackArray1[i];
}
else {
if (stackArray1[i].isItemEqual(stackArray2[i]))
{
outStack[i] = new ItemStack(stackArray1[i].getItem(), stackArray1[i].stackSize + stackArray2[i].stackSize);
}
else {
outStack[i] = null;
}
}
}
return outStack;
}
@Override
public void readFromNBT(NBTTagCompound tag)
{
super.readFromNBT(tag);
NBTHelper.readTanksFromNBT(new FluidTank[] { inputTank }, tag);
}
@Override
public void writeToNBT(NBTTagCompound tag)
{
super.writeToNBT(tag);
NBTHelper.writeTanksToNBT(new FluidTank[] { inputTank }, tag);
}
@Override
public ItemStack getStackInSlotOnClosing(int index)
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getInventoryStackLimit()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player)
{
// TODO Auto-generated method stub
return false;
}
@Override
public void openInventory(EntityPlayer player)
{
// TODO Auto-generated method stub
}
@Override
public void closeInventory(EntityPlayer player)
{
// TODO Auto-generated method stub
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack)
{
// TODO Auto-generated method stub
return false;
}
@Override
public int getField(int id)
{
// TODO Auto-generated method stub
return 0;
}
@Override
public void setField(int id, int value)
{
// TODO Auto-generated method stub
}
@Override
public int getFieldCount()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public void clear()
{
// TODO Auto-generated method stub
}
@Override
public String getName()
{
// TODO Auto-generated method stub
return null;
}
@Override
public boolean hasCustomName()
{
// TODO Auto-generated method stub
return false;
}
@Override
public IChatComponent getDisplayName()
{
// TODO Auto-generated method stub
return null;
}
@Override
public int[] getSlotsForFace(EnumFacing side)
{
// TODO Auto-generated method stub
return null;
}
@Override
public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction)
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction)
{
// TODO Auto-generated method stub
return false;
}
public enum Recipe
{
WaterSplitting(3, null, new FluidStack(FluidRegistry.WATER, 1000),
new ItemStack(ScienceModItems.element, 2, 0), new ItemStack(ScienceModItems.element, 1, 7));
public final int reqJarCount;
public final ItemStack reqItemStack;
public final FluidStack reqFluidStack;
// If there is only one output, the ItemStack on index 1 is null.
public final ItemStack[] outItemStack;
Recipe(int requiredJarCount, ItemStack requiredItemStack, FluidStack requiredFluidStack, ItemStack outputItemStack1,
ItemStack outputItemStack2)
{
reqJarCount = requiredJarCount;
reqItemStack = requiredItemStack;
reqFluidStack = requiredFluidStack;
outItemStack = new ItemStack[] { outputItemStack1, outputItemStack2 };
}
private boolean hasJars(ItemStack inputJarStack)
{
if (reqJarCount == 0) return true;
if (inputJarStack == null) return false;
return inputJarStack.stackSize >= reqJarCount;
}
private boolean hasItem(ItemStack inputItemStack)
{
if (reqItemStack != null)
{
// null check
if (inputItemStack == null) return false;
if (!inputItemStack.isItemEqual(reqItemStack)) return false;
if (inputItemStack.stackSize < reqItemStack.stackSize) return false;
}
return true;
}
private boolean hasFluid(FluidStack inputFluidStack)
{
if (reqFluidStack != null)
{
if (inputFluidStack == null) return false;
if (!inputFluidStack.containsFluid(reqFluidStack)) return false;
}
return true;
}
public boolean canProcessUsing(ItemStack inputJarStack, ItemStack inputItemStack, FluidStack inputFluidStack)
{
return hasJars(inputJarStack) && hasItem(inputItemStack) && hasFluid(inputFluidStack);
}
public ItemStack[] getOutputs()
{
return outItemStack;
}
}
}
| src/main/java/com/JasonILTG/ScienceMod/tileentity/TEElectrolyzer.java | package com.JasonILTG.ScienceMod.tileentity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IChatComponent;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import com.JasonILTG.ScienceMod.init.ScienceModItems;
import com.JasonILTG.ScienceMod.util.NBTHelper;
public class TEElectrolyzer extends TEMachine implements ISidedInventory
{
public static final int INVENTORY_SIZE = 4;
public static final int ITEM_INPUT_INDEX = 0;
public static final int JAR_INPUT_INDEX = 1;
public static final int[] OUTPUT_INDEX = { 2, 3 };
public static final int DEFAULT_MAX_PROGRESS = 100;
private Recipe currentRecipe;
private FluidTank inputTank;
public TEElectrolyzer()
{
// Initialize everything
super(DEFAULT_MAX_PROGRESS);
inventory = new ItemStack[INVENTORY_SIZE];
currentRecipe = null;
inputTank = new FluidTank(10000);
// The inventory slot at jar can only hold jars.
inventory[JAR_INPUT_INDEX] = new ItemStack(ScienceModItems.jar, 0);
}
@Override
public void update()
{
electrolyze();
}
private void electrolyze()
{
ItemStack[] currentOutput = tryElectrolyze(currentRecipe);
if (currentOutput != null)
{
// Continue current recipe.
currentProgress++;
}
// The current recipe is no longer valid. Once we find a new recipe we can reset the current progress and change over to the
// new recipe.
for (Recipe newRecipe : Recipe.values())
{
ItemStack[] attemptOutput = tryElectrolyze(newRecipe);
if (attemptOutput != null)
{
// Found a new recipe.
currentRecipe = newRecipe;
currentProgress = 1; // Account for the progress in the tick
}
}
if (currentProgress >= maxProgress)
{
// Time to output items and reset progress.
currentProgress = 0;
for (int i = 0; i < OUTPUT_INDEX.length; i++) {
inventory[OUTPUT_INDEX[i]].stackSize += currentOutput[i].stackSize;
}
}
}
/**
* Tries to electrolyze the inputs with the given recipe.
*
* @param recipeToUse the recipe to try
* @return
* If the operation is successful, returns the ItemStacks IN THE RIGHT ORDER so that they can be inserted into the output
* slots easily. If the operation is not successful, returns null.
*/
private ItemStack[] tryElectrolyze(Recipe recipeToUse)
{
// null check
if (recipeToUse == null) return null;
// If the recipe cannot use the input, the attempt fails.
if (!recipeToUse.canProcessUsing(inventory[JAR_INPUT_INDEX], inventory[ITEM_INPUT_INDEX], inputTank.getFluid()))
return null;
// Try to match output items with output slots.
ItemStack[] storedOutput = { inventory[OUTPUT_INDEX[0]], inventory[OUTPUT_INDEX[1]] };
ItemStack[] newOutput = recipeToUse.getOutputs();
ItemStack[] outputToAdd = new ItemStack[storedOutput.length];
// Use a copied version of the output inventory to prevent modification of the inventory
ItemStack[] predictedOutput = new ItemStack[storedOutput.length];
System.arraycopy(storedOutput, 0, predictedOutput, 0, storedOutput.length);
for (ItemStack stack : newOutput)
{
// Find out how to insert the stack
ItemStack[] pattern = findInsertPattern(stack, predictedOutput);
// If the return is null, that means we can't insert the stack.
if (pattern == null) return null;
// Add the pattern to the output and to the predicted pattern
outputToAdd = mergeStackArrays(outputToAdd, pattern);
predictedOutput = mergeStackArrays(predictedOutput, pattern);
}
return outputToAdd;
}
private ItemStack[] findInsertPattern(ItemStack stackToInsert, ItemStack[] insertTarget)
{
// null check
if (insertTarget == null) return null;
if (stackToInsert == null) return new ItemStack[insertTarget.length];
// Generate local copies to prevent modification of the parameters
ItemStack stack = stackToInsert.copy();
// insertTarget should not be modified in the method
// Initialize the output array
ItemStack[] insertPattern = new ItemStack[insertTarget.length];
// First pass through the array to look for already existing stacks of the same item
for (int i = 0; i < insertPattern.length; i++)
{
if (insertTarget[i] != null && insertTarget[i].isItemEqual(stackToInsert)
&& insertTarget[i].stackSize < insertTarget[i].getMaxStackSize())
{
// The target slot has a matching ItemStack and can store more
if (insertTarget[i].getMaxStackSize() - insertTarget[i].stackSize > stack.stackSize) {
// The stack has more than enough space
insertPattern[i] = stack;
// Insertion complete, return the pattern
return insertPattern;
}
// The target slot does not have enough space
insertPattern[i] = stack.splitStack(insertTarget[i].getMaxStackSize() - insertTarget[i].stackSize);
}
}
// Second pass through the array to look for any empty output slot
for (int i = 0; i < insertPattern.length; i++)
{
if (insertTarget[i] == null) {
insertPattern[i] = stack;
return insertPattern;
}
}
// If it comes to this, we can't insert output into the output slots.
return null;
}
private static ItemStack[] mergeStackArrays(ItemStack[] stackArray1, ItemStack[] stackArray2)
{
// null and length mismatch check
if (stackArray1 == null || stackArray2 == null || stackArray1.length != stackArray2.length) return null;
// Generate output
ItemStack[] outStack = new ItemStack[stackArray1.length];
for (int i = 0; i < outStack.length; i++) {
// For each ItemStack in the array
if (stackArray1[i] == null) {
outStack[i] = stackArray2[i];
}
else if (stackArray2[i] == null) {
outStack[i] = stackArray1[i];
}
else {
if (stackArray1[i].isItemEqual(stackArray2[i]))
{
outStack[i] = new ItemStack(stackArray1[i].getItem(), stackArray1[i].stackSize + stackArray2[i].stackSize);
}
else {
outStack[i] = null;
}
}
}
return outStack;
}
@Override
public void readFromNBT(NBTTagCompound tag)
{
super.readFromNBT(tag);
NBTHelper.readTanksFromNBT(new FluidTank[] { inputTank }, tag);
}
@Override
public void writeToNBT(NBTTagCompound tag)
{
super.writeToNBT(tag);
NBTHelper.writeTanksToNBT(new FluidTank[] { inputTank }, tag);
}
@Override
public ItemStack getStackInSlotOnClosing(int index)
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getInventoryStackLimit()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player)
{
// TODO Auto-generated method stub
return false;
}
@Override
public void openInventory(EntityPlayer player)
{
// TODO Auto-generated method stub
}
@Override
public void closeInventory(EntityPlayer player)
{
// TODO Auto-generated method stub
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack)
{
// TODO Auto-generated method stub
return false;
}
@Override
public int getField(int id)
{
// TODO Auto-generated method stub
return 0;
}
@Override
public void setField(int id, int value)
{
// TODO Auto-generated method stub
}
@Override
public int getFieldCount()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public void clear()
{
// TODO Auto-generated method stub
}
@Override
public String getName()
{
// TODO Auto-generated method stub
return null;
}
@Override
public boolean hasCustomName()
{
// TODO Auto-generated method stub
return false;
}
@Override
public IChatComponent getDisplayName()
{
// TODO Auto-generated method stub
return null;
}
@Override
public int[] getSlotsForFace(EnumFacing side)
{
// TODO Auto-generated method stub
return null;
}
@Override
public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction)
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction)
{
// TODO Auto-generated method stub
return false;
}
public enum Recipe
{
WaterSplitting(3, null, new FluidStack(FluidRegistry.WATER, 1000),
new ItemStack(ScienceModItems.element, 2, 0), new ItemStack(ScienceModItems.element, 1, 5));
public final int reqJarCount;
public final ItemStack reqItemStack;
public final FluidStack reqFluidStack;
// If there is only one output, the ItemStack on index 1 is null.
public final ItemStack[] outItemStack;
Recipe(int requiredJarCount, ItemStack requiredItemStack, FluidStack requiredFluidStack, ItemStack outputItemStack1,
ItemStack outputItemStack2)
{
reqJarCount = requiredJarCount;
reqItemStack = requiredItemStack;
reqFluidStack = requiredFluidStack;
outItemStack = new ItemStack[] { outputItemStack1, outputItemStack2 };
}
private boolean hasJars(ItemStack inputJarStack)
{
if (reqJarCount == 0) return true;
if (inputJarStack == null) return false;
return inputJarStack.stackSize >= reqJarCount;
}
private boolean hasItem(ItemStack inputItemStack)
{
if (reqItemStack != null)
{
// null check
if (inputItemStack == null) return false;
if (!inputItemStack.isItemEqual(reqItemStack)) return false;
if (inputItemStack.stackSize < reqItemStack.stackSize) return false;
}
return true;
}
private boolean hasFluid(FluidStack inputFluidStack)
{
if (reqFluidStack != null)
{
if (inputFluidStack == null) return false;
if (!inputFluidStack.containsFluid(reqFluidStack)) return false;
}
return true;
}
public boolean canProcessUsing(ItemStack inputJarStack, ItemStack inputItemStack, FluidStack inputFluidStack)
{
return hasJars(inputJarStack) && hasItem(inputItemStack) && hasFluid(inputFluidStack);
}
public ItemStack[] getOutputs()
{
return outItemStack;
}
}
}
| Fixed oxygen metadata | src/main/java/com/JasonILTG/ScienceMod/tileentity/TEElectrolyzer.java | Fixed oxygen metadata | <ide><path>rc/main/java/com/JasonILTG/ScienceMod/tileentity/TEElectrolyzer.java
<ide> public enum Recipe
<ide> {
<ide> WaterSplitting(3, null, new FluidStack(FluidRegistry.WATER, 1000),
<del> new ItemStack(ScienceModItems.element, 2, 0), new ItemStack(ScienceModItems.element, 1, 5));
<add> new ItemStack(ScienceModItems.element, 2, 0), new ItemStack(ScienceModItems.element, 1, 7));
<ide>
<ide> public final int reqJarCount;
<ide> public final ItemStack reqItemStack; |
|
JavaScript | mit | 688782c6653ea9cea0cf8d27dce194b253c0961e | 0 | ColorfulCakeChen/query-submit-canvas,ColorfulCakeChen/query-submit-canvas | export { Params, Base, PointDepthPoint };
import * as ValueMax from "../ValueMax.js";
//import * as ValueRange from "../Unpacker/ValueRange.js";
import * as ValueDesc from "../Unpacker/ValueDesc.js";
import * as ParamDesc from "../Unpacker/ParamDesc.js";
import * as Weights from "../Unpacker/Weights.js";
//import * as ReturnOrClone from "./ReturnOrClone.js";
import * as PointDepthPoint from "./PointDepthPoint.js";
import * as ChannelShuffler from "./ChannelShuffler.js";
/**
* Convolution block parameters.
*/
class Params extends Weights.Params {
/**
* If a parameter's value is null, it will be extracted from inputFloat32Array (i.e. by evolution).
*
* @return {boolean} Return false, if initialization failed.
*
* @override
*/
init( inputFloat32Array, byteOffsetBegin,
//!!! (2021/04/10 Remarked) They can not be evolved.
// sourceHeight, sourceWidth, sourceChannelCount,
stepCountPerBlock,
bChannelShuffler,
pointwise1ChannelCountRate,
depthwiseChannelMultiplierStep0, depthwiseFilterHeight, bBias, nActivationId, nActivationIdAtBlockEnd
) {
let parameterMap = new Map( [
//!!! (2021/04/10 Remarked) They can not be evolved.
// [ Params.sourceHeight, sourceHeight ],
// [ Params.sourceWidth, sourceWidth ],
// [ Params.sourceChannelCount, sourceChannelCount ],
[ Params.stepCountPerBlock, stepCountPerBlock ],
[ Params.bChannelShuffler, bChannelShuffler ],
[ Params.pointwise1ChannelCountRate, pointwise1ChannelCountRate ],
[ Params.depthwiseChannelMultiplierStep0, depthwiseChannelMultiplierStep0 ],
[ Params.depthwiseFilterHeight, depthwiseFilterHeight ],
[ Params.bBias, bBias ],
[ Params.nActivationId, nActivationId ],
[ Params.nActivationIdAtBlockEnd, nActivationIdAtBlockEnd ],
] );
return super.init( inputFloat32Array, byteOffsetBegin, parameterMap );
}
//!!! (2021/04/10 Remarked) They can not be evolved.
// get sourceHeight() { return this.parameterMapModified.get( Params.sourceHeight ); }
// get sourceWidth() { return this.parameterMapModified.get( Params.sourceWidth ); }
// get sourceChannelCount() { return this.parameterMapModified.get( Params.sourceChannelCount ); }
get stepCountPerBlock() { return this.parameterMapModified.get( Params.stepCountPerBlock ); }
get bChannelShuffler() { return this.parameterMapModified.get( Params.bChannelShuffler ); }
get pointwise1ChannelCountRate() { return this.parameterMapModified.get( Params.pointwise1ChannelCountRate ); }
/** @return {number} The number version of the step0's depthwise opertion. */
get depthwiseChannelMultiplierStep0() { return this.parameterMapModified.get( Params.depthwiseChannelMultiplierStep0 ); }
/** @return {string} The string version of the step0's depthwise opertion. */
get depthwiseChannelMultiplierStep0Name() { return Params.depthwiseChannelMultiplierStep0.getStringOfValue( this.depthwiseChannelMultiplierStep0 ); }
get depthwiseFilterHeight() { return this.parameterMapModified.get( Params.depthwiseFilterHeight ); }
get bBias() { return this.parameterMapModified.get( Params.bBias ); }
get nActivationId() { return this.parameterMapModified.get( Params.nActivationId ); }
get nActivationId() { return Params.nActivationId.getStringOfValue( this.nActivationId ); }
get nActivationIdAtBlockEndId() { return this.parameterMapModified.get( Params.nActivationIdAtBlockEnd ); }
get nActivationIdAtBlockEndName() { return Params.nActivationIdAtBlockEnd.getStringOfValue( this.nActivationIdAtBlockEnd ); }
}
// Define parameter descriptions.
//!!! (2021/04/10 Remarked) They can not be evolved.
// Params.sourceHeight = new ParamDesc.Int( "sourceHeight", 1, ( 10 * 1024 ) );
// Params.sourceWidth = new ParamDesc.Int( "sourceWidth", 1, ( 10 * 1024 ) );
// Params.sourceChannelCount = new ParamDesc.Int( "sourceChannelCount", 1, ( 10 * 1024 ) );
Params.stepCountPerBlock = new ParamDesc.Int( "stepCountPerBlock", 0, ( 10 * 1024 ) );
Params.bChannelShuffler = new ParamDesc.Bool( "bChannelShuffler" );
Params.pointwise1ChannelCountRate = new ParamDesc.Int( "pointwise1ChannelCountRate", 1, 2 );
Params.depthwiseChannelMultiplierStep0 = new ParamDesc.AvgMax_Or_ChannelMultiplier( "depthwiseChannelMultiplierStep0" );
Params.depthwiseFilterHeight = new ParamDesc.Int( "depthwiseFilterHeight", 1, 9 );
Params.bBias = new ParamDesc.Bool( "bBias" );
Params.nActivationId = new ParamDesc.ActivationFunction( "nActivationId" );
Params.nActivationIdAtBlockEnd = new ParamDesc.ActivationFunction( "nActivationIdAtBlockEnd" );
/**
* Implement a block of ( depthwise convolution and pointwise convolution ) or ShuffleNetV2 (with 2 output channel groups) or MobileNetV1
* or MobileNetV2.
*
*
* @member {function} apply_and_destroy_or_keep
* This is a method. It has an parameter inputTensor (tf.tensor3d) represents the image ( height x width x channel ) which
* will be processed. It returns a new tf.tensor3d. All other tensors will be disposed. But inputTensor could be kept
* (if ( bKeepInputTensor == true ) ) or disposed (if ( bKeepInputTensor == false ) ). In fact, this method calls one of
* apply_and_destroy_or_keep_NotChannelShuffle_NotAddInputToOutput(), apply_and_destroy_or_keep_ChannelShuffle(),
* apply_and_destroy_or_keep_AddInputToOutput() according to the init()'s parameters.
*
* @member {number} outputChannelCount
* The output channel count of this block's last step.
*
* @member {PointDepthPoint.Base} step0
* The first step computation of this block.
*
* @member {PointDepthPoint.Base} stepLast
* The last step computation of this block. It may be the same as this.step0 when there is only one step inside this block.
*
* @see ChannelShuffler.ConcatPointwiseConv
*/
class Base {
/**
* Generator for initializing this object.
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* Some new progressToAdvance will be created and added to progressParent. The created progressToAdvance will be
* increased when every time advanced. The progressParent.getRoot() will be returned when every time yield.
*
* @param {Float32Array} inputFloat32Array
* A Float32Array whose values will be interpreted as weights.
*
* @param {number} byteOffsetBegin
* The position to start to decode from the inputFloat32Array. This is relative to the inputFloat32Array.buffer
* (not to the inputFloat32Array.byteOffset).
*
* @param {number} sourceHeight
* The height of the source image which will be processed by apply_and_destroy_or_keep(). This should always be specified and can
* not be null (i.e. it will never be extracted from inputFloat32Array and never by evolution).
*
* @param {number} sourceWidth
* The width of the source image which will be processed by apply_and_destroy_or_keep().c This should always be specified and can
* not be null (i.e. it will never be extracted from inputFloat32Array and never by evolution).
*
* @param {number} sourceChannelCount
* The channel count of the source image. It may be the output channel count of the previous convolution block, so it could be large.
* This should always be specified and can not be null (i.e. it will never be extracted from inputFloat32Array and never by evolution).
*
* @param {number} stepCountPerBlock
* There are how many step inside this block. If null, it will be extracted from inputFloat32Array (i.e. by evolution). If zero or
* negative (<= 0), every block will use only one tf.depthwiseConv2d( strides = 1, pad = "valid" ) for shrinking sourceHeight
* (minus ( filterHeight - 1 )). If positive (>= 1), every block will use one tf.depthwiseConv2d( strides = 2, pad = "same" ) to shrink
* (halve height x width) and use ( stepCountPerBlock - 1 ) times tf.depthwiseConv2d( strides = 1, pad = "same" ) until the block end.
*
* @param {boolean} bChannelShuffler
* If true, will like ShuffleNetV2 (i.e. split and concat channels). If false, will like MobileNetV1 or MobileNetV2 (i.e. add input
* to output). If null, it will be extracted from inputFloat32Array (i.e. by evolution). If ( stepCountPerBlock <= 0 ), this flag
* will be ignored.
*
* @param {number} pointwise1ChannelCountRate
* The first 1x1 pointwise convolution output channel count over of the second 1x1 pointwise convolution output channel count.
* That is, pointwise1ChannelCount = ( pointwise2ChannelCount * pointwise1ChannelCountRate ). If null, it will be extracted from
* inputFloat32Array (i.e. by evolution).
* - If ( stepCountPerBlock <= 0 ), this rate will be ignored because there will be no first 1x1 pointwise.
* - If ( bChannelShuffler == true ) and ( pointwise1ChannelCountRate == 1 ), will like ShuffleNetV2.
* - If ( bChannelShuffler == false ) and ( pointwise1ChannelCountRate == 1 ), will like MobileNetV1.
* - If ( bChannelShuffler == false ) and ( pointwise1ChannelCountRate > 1 ), will like MobileNetV2.
*
//!!! ...unfinished...
* @param {number} depthwiseChannelMultiplierStep0
* The depthwise convolution of the first step (Step 0) will expand input channel by this factor. If null, it will be extracted
* from inputFloat32Array (i.e. by evolution). If non-null, it should be integer between [ -2, 32 ]:
* - Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.AVG (-2): average pooling.
* - Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.MAX (-1): max pooling.
* - Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.NONE (0): this will be adjusted to 1 forcibly (always needs depthwise operation).
* - positive integer between [ 1, 32 ]: depthwise convolution and the number indicates channel multiplier.
*
* @param {boolean} bBias
* If true, there will be a bias after every convolution. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
*
* @param {string} nActivationId
* The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) after the convolution. If null, it will be extracted
* from inputFloat32Array (i.e. by evolution).
*
* @param {string} nActivationIdAtBlockEnd
* The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) after the convolution of the last PointDepthPoint's
* pointwise2ActivationId of this block. If null, it will be extracted from inputFloat32Array (i.e. by evolution). If the output of
* this block needs to be any arbitrary value, it is recommended not to use activation at the end of this block
* (i.e. nActivationIdAtBlockEnd == ValueDesc.ActivationFunction.Singleton.Ids.NONE) so that it will not be restricted by the range
* of the activation function.
*
//!!! ...unfinished...
//!!! ...unfinished... (2021/04/09) How to know now is MobileNetV2 (not MobileNetV1)? Maybe according to ( pointwise1ChannelCountRate > 1 )?
// Since pointwise2ActivationId is always NONE in MobileNetV2 (i.e. ( bChannelShuffler == false ), the nActivationIdAtBlockEnd is never used in MobileNetV2.
*
* @param {boolean} bKeepInputTensor
* If true, apply_and_destroy_or_keep() will not dispose inputTensor (i.e. keep). If it is null, it will be viewed as falsy
* (i.e. it will never be extracted from inputFloat32Array and never by evolution).
*
* @yield {ValueMax.Percentage.Aggregate}
* Yield ( value = progressParent.getRoot() ) when ( done = false ).
*
* @yield {boolean}
* Yield ( value = true ) when ( done = true ) successfully.
* Yield ( value = false ) when ( done = true ) failed.
*
* @see PointDepthPoint.Base.initer()
*/
* initer(
progressParent,
inputFloat32Array, byteOffsetBegin,
sourceHeight, sourceWidth, sourceChannelCount,
stepCountPerBlock,
bChannelShuffler,
pointwise1ChannelCountRate,
depthwiseChannelMultiplierStep0, depthwiseFilterHeight,
bBias, nActivationId, nActivationIdAtBlockEnd,
bKeepInputTensor
) {
// Both MobileNetV3 and ShuffleNetV2:
// - They all do not use (depthwise convolution) channelMultiplier.
// - They all use 1x1 (pointwise) convolution to expand channel count.
// - They all use 1x1 (pointwise) convolution before depthwise convolution.
// - They all use activation function after first pointwise convolution.
// - They all use depthwise convolution with ( pad = "same" ).
// - They all use depthwise convolution with ( strides = 2 ) for shrinking (halving) height x width.
// - They all do not use bias after pointwise and depthwise convolution.
//
// Inisde one of their block, three convolutions are used:
// A) 1x1 (pointwise) convolution, with activation.
// B) depthwise convolution, (ShuffleNetV2) without or (MobileNetV2) with activation.
// C) 1x1 (pointwise) convolution, (ShuffleNetV2) with or (MobileNetV2) without activation.
//
// In MobileNetV3, convolution A expands channel count (with activation), convolution C shrinks channel count (without activation).
// It may use squeeze-and-excitation after convolution B (without activation). When there is necessary to increase output channel
// count (usually in step 0 of a block), the convolution C is responsible for this.
//
// In ShuffleNetV2, convolution A (with activation), convolution B (without activation) and convolution C (with activation) never
// change channel count. When there is necessary to increase output channel count (usually in step 0 of a block), it expands channel
// count by concatenating two shrinked (halven) height x width.
// 0. Prepare
//!!! ...unfinished...
// Estimate the maximum value of progress.
let progressMax =
1 // for extracting parameters from inputFloat32Array.
+ 1 // for extracting pointwise1 filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for extracting depthwise filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for extracting pointwise2 filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for all pointwise1-depthwise-pointwise2 filters (and biases) ready.
;
let progressRoot = progressParent.getRoot();
let progressToAdvance = progressParent.addChild( new ValueMax.Percentage.Concrete( progressMax ) );
this.disposeTensors();
this.nextByteOffsetBegin = byteOffsetBegin;
this.sourceHeight = sourceHeight;
this.sourceWidth = sourceWidth;
this.sourceChannelCount = sourceChannelCount;
//!!! ...unfinished...
// 1. Extract parameters.
this.params = new Params();
let bParamsInitOk
= this.params.init( inputFloat32Array, byteOffsetBegin,
pointwise1ChannelCount, bPointwise1Bias, pointwise1ActivationId,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, bDepthwiseBias, depthwiseActivationId,
pointwise2ChannelCount, bPointwise2Bias, pointwise2ActivationId,
bAddInputToOutput );
if ( !bParamsInitOk )
return false; // e.g. input array does not have enough data.
this.nextByteOffsetBegin = this.params.defaultByteOffsetEnd;
//!!! ...unfinished...
// Get parameters' real (adjusted) values.
{
pointwise1ChannelCount = this.pointwise1ChannelCount;
bPointwise1Bias = this.bPointwise1Bias;
pointwise1ActivationId = this.pointwise1ActivationId;
depthwise_AvgMax_Or_ChannelMultiplier = this.depthwise_AvgMax_Or_ChannelMultiplier;
depthwiseFilterHeight = this.depthwiseFilterHeight;
depthwiseStridesPad = this.depthwiseStridesPad;
bDepthwiseBias = this.bDepthwiseBias;
depthwiseActivationId = this.depthwiseActivationId;
pointwise2ChannelCount = this.pointwise2ChannelCount;
bPointwise2Bias = this.bPointwise2Bias;
pointwise2ActivationId = this.pointwise2ActivationId;
bAddInputToOutput = this.bAddInputToOutput;
}
++progressToAdvance.value;
yield progressRoot; // Parameters extracted. Report progress.
this.stepCountPerBlock = stepCountPerBlock;
//!!! ...unfinished... (2021/04/10)
// Perhaps, Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.NONE (0) (no depthwise operation) could be viewed as ( bChannelShuffler == true ).
// Because it is not possible to change depthwiseChannelMultiplier in ShuffleNetV2 (it is always ( depthwiseChannelMultiplier == 1 )).
// (WRONG! it is possible to change depthwiseChannelMultiplier in ShuffleNetV2.)
// This could also reduce one parameter (drop the bChannelShuffler parameter).
this.bChannelShuffler = bChannelShuffler;
this.pointwise1ChannelCountRate = pointwise1ChannelCountRate;
//!!! ...unfinished... (2021/04/10) Place this adjustment after Params.init().
// The depthwise channel multipler of the step 0 can not be Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.NONE (0).
// Otherwise, the input image will not be shrinked a little (for ( stepCountPerBlock <= 0 )) or will not be halven
// (for ( stepCountPerBlock >= 1 ). So force to 1 at least (always needs depthwise operation).
if ( depthwiseChannelMultiplierStep0 == 0 )
depthwiseChannelMultiplierStep0 = 1;
this.depthwiseChannelMultiplierStep0 = depthwiseChannelMultiplierStep0;
let depthwiseFilterWidth = depthwiseFilterHeight; // Assume depthwise filter's width equals its height.
this.depthwiseFilterHeight = depthwiseFilterHeight;
this.depthwiseFilterWidth = depthwiseFilterWidth;
this.bBias = bBias;
this.nActivationId = nActivationId;
this.nActivationIdAtBlockEnd = nActivationIdAtBlockEnd;
this.bKeepInputTensor = bKeepInputTensor;
this.bAddInputToOutput = !bChannelShuffler; // ChannelShuffler or AddInputToOutput, but not both. They are all for achieving skip connection.
let pointwise1Bias = bBias;
let pointwise1ActivationId = nActivationId;
let depthwiseBias = bBias;
let depthwiseActivationId = nActivationId;
let pointwise2Bias = bBias;
let pointwise2ActivationId = nActivationId;
if ( stepCountPerBlock <= 0 ) { // Not ShuffleNetV2, Not MobileNetV2.
// Only one step (i.e. step 0 ) for depthwise operation with ( strides = 1, pad = "valid" )
// for shrinking sourceHeight (minus ( filterHeight - 1 )).
let pointwise1ChannelCount = 0; // no pointwise convolution before depthwise convolution.
let pointwise2ChannelCount;
let depthwise_AvgMax_Or_ChannelMultiplier = depthwiseChannelMultiplierStep0; // (Can not be zero.)
if ( depthwise_AvgMax_Or_ChannelMultiplier > 0 ) { // Depthwise convolution.
pointwise2ChannelCount = sourceChannelCount * depthwiseChannelMultiplierStep0;
} else { // Avg pooling, or Max pooling.
pointwise2ChannelCount = sourceChannelCount; // The output channel count of average (or max) pooling is the same as input channel count.
}
let depthwiseStridesPad = 0; // ( depthwiseStrides == 1 ) and ( depthwisePad == "valid" ) so that shrinking sourceHeight a little.
// This is the last step of this block (i.e. at-block-end) because ( stepCountPerBlock <= 0 ) means there is only one step inside
// this block. And a different activation function may be used after pointwise2 convolution.
pointwise2ActivationId = nActivationIdAtBlockEnd;
let step0 = this.step0 = new PointDepthPoint.Base();
step0.init(
sourceChannelCount,
pointwise1ChannelCount, pointwise1Bias, pointwise1ActivationId,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, depthwiseBias, depthwiseActivationId,
pointwise2ChannelCount, pointwise2Bias, pointwise2ActivationId,
false, // It is not possible to add-input-to-output, because ( depthwisePad == "valid" ).
bKeepInputTensor // Step 0 may or may not keep input tensor according to caller's necessary.
);
this.stepLast = step0;
this.apply_and_destroy_or_keep = Base.apply_and_destroy_or_keep_NotChannelShuffle_NotAddInputToOutput;
this.outputChannelCount = step0.outputChannelCount;
} else { // ShuffleNetV2, or MobileNetV2.
// Step 0.
//
// The special points of a block's step 0 are:
// - halve the height x width. (Both ShuffleNetV2 and MobileNetV2) (by depthwise convolution with strides = 2)
// - Double channels. (By concat if ShuffleNetV2. By second pointwise if MobileNetV2.)
// - Expand channels by channelMultiplier of depthwise convolution. (Both ShuffleNetV2 and MobileNetV2 do not have this. It is added by us.)
let step0, step0Branch;
{
let depthwise_AvgMax_Or_ChannelMultiplier = depthwiseChannelMultiplierStep0; // (Can not be zero.)
// Step 0 is responsibile for halving input's height (and width).
let depthwiseStridesPad = 2; // ( depthwiseStrides == 2 ) and ( depthwisePad == "same" )
let pointwise1ChannelCount, pointwise2ChannelCount;
if ( bChannelShuffler ) { // ShuffleNetV2.
pointwise2ChannelCount = sourceChannelCount * 1; // In ShuffleNetV2, all convolutions do not change channel count
// If an operation has no activation function, it can have no bias too. Because the next operation's bias can achieve the same result.
depthwiseBias = false;
// In ShuffleNetV2, depthwise convolution does not have activation function.
depthwiseActivationId = PointDepthPoint.Params.Activation.Ids.NONE;
} else { // MobileNetV1, or MobileNetV2.
pointwise2ChannelCount = sourceChannelCount * 2; // The output channel count of step 0 of MobileNetV2 is twice as input.
// If an operation has no activation function, it can have no bias too. Because the next operation's bias can achieve the same result.
pointwise2Bias = false;
//!!! ...unfinished... (2021/04/09) How to know now is MobileNetV2 (not MobileNetV1)? Maybe according to ( pointwise1ChannelCountRate > 1 )?
// In MobileNetV2, the second 1x1 pointwise convolution does not have activation function in default.
//
// But it could be changed by nActivationIdAtBlockEnd for the last step of the block.
pointwise2ActivationId = PointDepthPoint.Params.Activation.Ids.NONE;
}
// If there is only one step, this (step 0) is also the last step of this block (i.e. at-block-end) and a different activation
// function may be used after pointwise2 convolution.
//
// Even if in MobileNetV2 (pointwise2 convolution does not have activation function in default), this is still true.
if ( 1 == stepCountPerBlock ) {
pointwise2ActivationId = nActivationIdAtBlockEnd;
}
// If ( pointwise1ChannelCount < pointwise2ChannelCount ), similiar to ResNet.
// If ( pointwise1ChannelCount == pointwise2ChannelCount ), similiar to MobileNetV1 or ShufffleNetV2.
// If ( pointwise1ChannelCount > pointwise2ChannelCount ), similiar to MobileNetV2.
pointwise1ChannelCount = pointwise2ChannelCount * pointwise1ChannelCountRate;
step0 = this.step0 = new PointDepthPoint.Base();
step0.init(
sourceChannelCount,
pointwise1ChannelCount, pointwise1Bias, pointwise1ActivationId,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, depthwiseBias, depthwiseActivationId,
pointwise2ChannelCount, pointwise2Bias, pointwise2ActivationId,
// In MobileNet2, step 0 is not possible, because output channel count is tiwce as input.
// In ShuffleNetV2, the skipping connection is achieved by concatenating.
// So, it is not necessary to add input to output.
false,
bKeepInputTensor // Step 0 may or may not keep input tensor according to caller's necessary.
);
// Step0's branch (ShuffleNetV2)
//
// The step 0 of ShuffleNetV2 has a branch which also halves the height and width by depthwise convolution. And it does not have
// the first 1x1 (pointwise) convolution. But it has the second 1x1 (pointwise) convolution.
if ( bChannelShuffler ) {
this.step0Branch = step0Branch = new PointDepthPoint.Base();
step0Branch.init(
sourceChannelCount,
// ShuffleNetV2 Step0's branch does not have the first 1x1 pointwise convolution before depthwise convolution ( strides = 2 ).
0, false, ValueDesc.ActivationFunction.Singleton.Ids.NONE,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, depthwiseBias, depthwiseActivationId,
pointwise2ChannelCount, pointwise2Bias, pointwise2ActivationId,
false, // In ShuffleNetV2, the skipping connection is achieved by concatenating. So, it is not necessary to add input to output.
true // This is the only case that must keep input tensor, because the input tensor need be re-used by the main path of setp 0.
);
// Pre-allocated array (with only two elements) for improving performance by reducing memory re-allocation.
this.concatTensorArray = new Array( 2 );
// Bind in step 0's logic, because step 1 (2, 3, ...) may not existed.
this.apply_and_destroy_or_keep = Base.apply_and_destroy_or_keep_ChannelShuffle;
this.outputChannelCount = step0.outputChannelCount + step0Branch.outputChannelCount;
} else {
// Bind in step 0's logic, because step 1 (2, 3, ...) may not existed.
this.apply_and_destroy_or_keep = Base.apply_and_destroy_or_keep_AddInputToOutput;
this.outputChannelCount = step0.outputChannelCount;
}
}
// Step 1, 2, 3, ...
if ( stepCountPerBlock > 0 ) {
let depthwise_AvgMax_Or_ChannelMultiplier = depthwiseChannelMultiplierStep0;
if ( depthwise_AvgMax_Or_ChannelMultiplier >= 0 ) { // Depthwise convolution.
// In non-step0, it should not expand channel. Only step 0 can have ( channelMultiplier > 1 ). So, force to 1.
depthwise_AvgMax_Or_ChannelMultiplier = 1;
} else { // Avg pooling, or Max pooling.
// Do nothing. Keep going.
}
// Force to ( depthwiseStrides == 1 ), because only step 0 (i.e. not here) should halve input's height (and width).
let depthwiseStridesPad = 1; // ( depthwiseStrides == 1 ) and ( depthwisePad == "same" )
// In ShuffleNetV2, the input channel count of step 1 (2, 3, ...) is the concatenated output channel count of the
// main and branch of step 0. However, they will be splitted (by channel shuffler) into two channel groups. So every
// channel group has just only half of concatenated channel count of step 0 (i.e. not including the step0Branch).
//
// In MobileNetV2, the input channel count of step 1 (2, 3, ...) is the output channel count of the step 0.
//
// In a word, they are all the same as step0.outputChannelCount.
let channelCount_pointwise1Before = step0.outputChannelCount;
let pointwise2ChannelCount = channelCount_pointwise1Before; // Every step will output the same channel count as input.
// The first 1x1 pointwise convolution can change channel count.
let pointwise1ChannelCount = pointwise2ChannelCount * pointwise1ChannelCountRate;
// In ShuffleNetV2, there is a channel shuffler in every step (except setp 0). It is shared by these steps in the same block.
if ( bChannelShuffler ) {
let concatenatedChannelCount = step0.outputChannelCount + step0Branch.outputChannelCount;
let sourceConcatenatedShape = this.sourceConcatenatedShape = [ sourceHeight, sourceWidth, concatenatedChannelCount ];
let outputGroupCount = 2; // ShuffleNetV2 always uses two (depthwise convolution) groups.
//!!! (2021/04/10) ...unfinished... Using ChannelShuffler.ConcatPointwiseConv instead.
this.concatGather = new ChannelShuffler.ConcatGather();
this.concatGather.init( sourceConcatenatedShape, outputGroupCount );
this.concatPointwiseConv = new ChannelShuffler.ConcatPointwiseConv();
this.concatPointwiseConv.init( sourceConcatenatedShape, outputGroupCount );
}
this.steps1After = new Array( stepCountPerBlock - 1 ); // "- 1" because this array does not include step0.
for ( let i = 0; i < this.steps1After.length; ++i ) {
// If this is the last step of this block (i.e. at-block-end), a different activation function may be used after
// pointwise2 convolution.
//
// Even if in MobileNetV2 (pointwise2 convolution does not have activation function in default), this is still true.
if ( i == ( this.steps1After.length - 1 ) ) {
pointwise2ActivationId = nActivationIdAtBlockEnd;
}
let step = new PointDepthPoint.Base();
step.init(
channelCount_pointwise1Before,
pointwise1ChannelCount, pointwise1Bias, pointwise1ActivationId,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, depthwiseBias, depthwiseActivationId,
pointwise2ChannelCount, pointwise2Bias, pointwise2ActivationId,
this.bAddInputToOutput,
false // No matter bKeepInputTensor, all steps (except step 0) should not keep input tensor.
);
this.steps1After[ i ] = step;
}
if ( 1 == stepCountPerBlock ) {
this.stepLast = this.step0; // If there is only one step, it is also the last step.
} else {
this.stepLast = this.steps1After[ this.steps1After.length - 1 ]; // Shortcut to the last step.
}
}
}
}
/**
* Initialize this object by calling initer() and advance the generator by loop until done.
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* If null, a temporary progress object will be created.
*
* @return {boolean}
* Return true if successfully (and progressParent.valuePercentage will be equal to 100).
* Return false if failed (and progressParent.valuePercentage will be less than 100).
*
* @see PointDepthPoint.Base.init()
*/
init(
progressParent,
inputFloat32Array, byteOffsetBegin,
sourceHeight, sourceWidth, sourceChannelCount,
stepCountPerBlock,
bChannelShuffler,
pointwise1ChannelCountRate,
depthwiseChannelMultiplierStep0, depthwiseFilterHeight, bBias, nActivationId, nActivationIdAtBlockEnd,
bKeepInputTensor
) {
progressParent = progressParent || ( new ValueMax.Percentage.Aggregate() );
let initer = this.initer(
progressParent,
inputFloat32Array, byteOffsetBegin,
sourceHeight, sourceWidth, sourceChannelCount,
stepCountPerBlock,
bChannelShuffler,
pointwise1ChannelCountRate,
depthwiseChannelMultiplierStep0, depthwiseFilterHeight, bBias, nActivationId, nActivationIdAtBlockEnd,
bKeepInputTensor
);
let initerNext;
do {
initerNext = initer.next();
} while ( ! initerNext.done ); // When ( false == initerNext.done ), the ( initerNext.value ) will be progressParent.getRoot().
let bInitOk = initerNext.value; // When ( true == initerNext.done ), the ( initerNext.value ) will be initialization successfully or failed.
return bInitOk;
}
disposeTensors() {
//!!! (2021/04/10) ...unfinished... Using ChannelShuffler.ConcatPointwiseConv instead.
if ( this.concatGather ) {
this.concatGather.disposeTensors();
this.concatGather = null;
}
if ( this.concatPointwiseConv ) {
this.concatPointwiseConv.disposeTensors();
this.concatPointwiseConv = null;
}
if ( this.concatTensorArray ) {
this.concatTensorArray = null;
}
if ( this.step0 ) {
this.step0.disposeTensors();
this.step0 = null;
}
if ( this.step0Branch ) {
this.step0Branch.disposeTensors();
this.step0Branch = null;
}
if ( this.steps1After ) {
for ( let step of this.steps1After ) {
step.disposeTensors();
}
this.steps1After = null;
}
this.stepLast = null; // It has already de disposed by this.step0 or this.steps1After.
}
/** Process input, destroy input, return result. (For Not ShuffleNetV2 and Not MobileNetV2.)
*
* @param {Block} this
* This method should not be called directly. It should be called by calling apply_and_destroy_or_keep().
*
* @param {tf.tensor3d} inputTensor
* The image which will be processed. This inputTensor may or may not be disposed according to init()'s bKeepInputTensor.
*
* @return {tf.tensor3d} Return a new tensor. All other intermediate tensors were disposed.
*/
static apply_and_destroy_or_keep_NotChannelShuffle_NotAddInputToOutput( inputTensor ) {
return this.step0.apply_and_destroy_or_keep( inputTensor );
}
//!!! ...unfinished... (2021/04/13) (Our) Adjusted ShuffleNetV2:
//
// Since channel shuffler could achieved efficiently by pointwise convolution, it may be possible to combine the pointwise2
// convolution (after depthwise convolution) and the pointwise convolution (of channel shuffler). That is:
// - Concatenate the output of depthwise convolution and the other output group.
// - Pointwise convolution to generate output group 1.
// - Pointwise convolution to generate output group 2.
//
// In order to achieve it, there is a pre-condition: the pointwise2 convolution (after depthwise convolution) do not
// have bias and activation function. The reason is that the channel shuffler (achieved by pointwise convolution) uses
// only pointwise convolution without bias and activation function.
//
//
// If the poitwise1 convolution (of every step (include step 0 too)) could be discarded, the step 0 and step 0's branch could
// be achieved simultaneously by:
// - once depthwise convolution (channelMultipler = 2, strides = 2, pad = same, bias, COS).
// - No need to concatenate because the above operation already double channel count.
// - twice pointwise2 convolution (no bias, no activation function).
//
// And, the step 1 (, 2, 3, ...) could be achieved by:
// - once depthwise convolution (channelMultipler = 1, strides = 1, pad = same, bias, COS).
// - concatenate.
// - twice pointwise2 convolution (no bias, no activation function).
//
// And, the last step of the block could be achieved by:
// - once depthwise convolution (channelMultipler = 1, strides = 1, pad = same, bias, COS).
// - concatenate.
// - once pointwise2 convolution (no bias, no activation function).
//
// Note that:
// - The depthwise convolution (channelMultipler = 2, strides = 2) of step 0 achieves simultaneously two depthwise
// convolution (channelMultipler = 1, strides = 2) of step 0 and step 0's branch. So, it is one less depthwise
// convolution, and one less concatenating.
//
// - The twice pointwise2 convolution (no bias, no activation function) achieves not only pointwise convolution but
// also channel shuffling. So, it is one less pointwise convolution.
//
// - The once pointwise2 convolution (no bias, no activation function) of last step achieves simultaneously pointwise
// convolution, channel shuffling, and concatenating. So, it is not only one less pointwise convolution, but also
// one less concatenating.
//
/** Process input, destroy input, return result. (For ShuffleNetV2.)
*
* @param {Block} this
* This method should not be called directly. It should be called by calling apply_and_destroy_or_keep().
*
* @param {tf.tensor3d} inputTensor
* The image which will be processed. This inputTensor may or may not be disposed according to init()'s bKeepInputTensor.
*
* @return {tf.tensor3d} Return a new tensor. All other intermediate tensors were disposed.
*/
static apply_and_destroy_or_keep_ChannelShuffle( inputTensor ) {
// Keep data as local variables for improving performance.
//!!! ...unfinished... Compare performance to call concatGather.concatGather() directly.
//!!! (2021/04/08) ...unfinished... Using ChannelShuffler.ConcatPointwiseConv instead.
let lastAxisId = this.concatGather.shuffleInfo.lastAxisId;
// There are exactly two output channel groups, take them out from array. (for reducing array access cost.)
let group0_channelIndicesTensor1d = this.concatGather.shuffledChannelIndicesTensor1dArray[ 0 ];
let group1_channelIndicesTensor1d = this.concatGather.shuffledChannelIndicesTensor1dArray[ 1 ];
let concatTensorArray = this.concatTensorArray; // Keep pre-allocated array (with two elements) as local variables for improving performance.
// tensor of convolution group 0, tensor of convolution group 1, new tensor of convolution group 1, tensor of concatenation of group 0 and 1.
let t0, t1, t1New, concatenatedTensor;
// Step 0.
concatTensorArray[ 0 ] = t0 = this.step0Branch.apply_and_destroy_or_keep( inputTensor ); // Branch (will NOT destroy input tensor).
concatTensorArray[ 1 ] = t1 = this.step0 .apply_and_destroy_or_keep( inputTensor ); // Main Path (may or may not destroy input tensor).
concatenatedTensor = tf.concat( concatTensorArray, lastAxisId );
t0.dispose(); // Dispose all intermediate (temporary) data.
t1.dispose(); // Dispose all intermediate (temporary) data.
// Step 1, 2, 3, ...
let step;
for ( let i = 0; i < this.steps1After.length; ++i ) {
step = this.steps1After[ i ];
// shuffle and split by gather (one operation achieves two operations).
t0 = concatenatedTensor.gather( group0_channelIndicesTensor1d, lastAxisId );
t1 = concatenatedTensor.gather( group1_channelIndicesTensor1d, lastAxisId );
concatenatedTensor.dispose(); // Dispose all intermediate (temporary) data.
concatTensorArray[ 0 ] = t0; // Branch do nothing (as a shortcut).
concatTensorArray[ 1 ] = t1New = step.apply_and_destroy_or_keep( t1 ); // Main path is processed.
concatenatedTensor = tf.concat( concatTensorArray, lastAxisId );
t0.dispose(); // Dispose all intermediate (temporary) data.
t1New.dispose(); // Dispose all intermediate (temporary) data.
}
return concatenatedTensor;
}
/** Process input, destroy input, return result. (For MobileNetV2.)
*
* @param {Block} this
* This method should not be called directly. It should be called by calling apply_and_destroy_or_keep().
*
* @param {tf.tensor3d} inputTensor
* The image which will be processed. This inputTensor may or may not be disposed according to init()'s bKeepInputTensor.
*
* @return {tf.tensor3d} Return a new tensor. All other intermediate tensors were disposed.
*/
static apply_and_destroy_or_keep_AddInputToOutput( inputTensor ) {
let t, tNew;
// Step 0.
t = this.step0.apply_and_destroy_or_keep( inputTensor );
// Step 1, 2, 3, ...
let step;
for ( let i = 0; i < this.steps1After.length; ++i ) {
step = this.steps1After[ i ];
t = step.apply_and_destroy_or_keep( t );
}
return t;
}
}
| CNN/Conv/Block.js | export { Params, Base, PointDepthPoint };
import * as ValueMax from "../ValueMax.js";
//import * as ValueRange from "../Unpacker/ValueRange.js";
import * as ValueDesc from "../Unpacker/ValueDesc.js";
import * as ParamDesc from "../Unpacker/ParamDesc.js";
import * as Weights from "../Unpacker/Weights.js";
//import * as ReturnOrClone from "./ReturnOrClone.js";
import * as PointDepthPoint from "./PointDepthPoint.js";
import * as ChannelShuffler from "./ChannelShuffler.js";
/**
* Convolution block parameters.
*/
class Params extends Weights.Params {
/**
* If a parameter's value is null, it will be extracted from inputFloat32Array (i.e. by evolution).
*
* @return {boolean} Return false, if initialization failed.
*
* @override
*/
init( inputFloat32Array, byteOffsetBegin,
//!!! (2021/04/10 Remarked) They can not be evolved.
// sourceHeight, sourceWidth, sourceChannelCount,
stepCountPerBlock,
bChannelShuffler,
pointwise1ChannelCountRate,
depthwiseChannelMultiplierStep0, depthwiseFilterHeight, bBias, nActivationId, nActivationIdAtBlockEnd
) {
let parameterMap = new Map( [
//!!! (2021/04/10 Remarked) They can not be evolved.
// [ Params.sourceHeight, sourceHeight ],
// [ Params.sourceWidth, sourceWidth ],
// [ Params.sourceChannelCount, sourceChannelCount ],
[ Params.stepCountPerBlock, stepCountPerBlock ],
[ Params.bChannelShuffler, bChannelShuffler ],
[ Params.pointwise1ChannelCountRate, pointwise1ChannelCountRate ],
[ Params.depthwiseChannelMultiplierStep0, depthwiseChannelMultiplierStep0 ],
[ Params.depthwiseFilterHeight, depthwiseFilterHeight ],
[ Params.bBias, bBias ],
[ Params.nActivationId, nActivationId ],
[ Params.nActivationIdAtBlockEnd, nActivationIdAtBlockEnd ],
] );
return super.init( inputFloat32Array, byteOffsetBegin, parameterMap );
}
//!!! (2021/04/10 Remarked) They can not be evolved.
// get sourceHeight() { return this.parameterMapModified.get( Params.sourceHeight ); }
// get sourceWidth() { return this.parameterMapModified.get( Params.sourceWidth ); }
// get sourceChannelCount() { return this.parameterMapModified.get( Params.sourceChannelCount ); }
get stepCountPerBlock() { return this.parameterMapModified.get( Params.stepCountPerBlock ); }
get bChannelShuffler() { return this.parameterMapModified.get( Params.bChannelShuffler ); }
get pointwise1ChannelCountRate() { return this.parameterMapModified.get( Params.pointwise1ChannelCountRate ); }
/** @return {number} The number version of the step0's depthwise opertion. */
get depthwiseChannelMultiplierStep0() { return this.parameterMapModified.get( Params.depthwiseChannelMultiplierStep0 ); }
/** @return {string} The string version of the step0's depthwise opertion. */
get depthwiseChannelMultiplierStep0Name() { return Params.depthwiseChannelMultiplierStep0.getStringOfValue( this.depthwiseChannelMultiplierStep0 ); }
get depthwiseFilterHeight() { return this.parameterMapModified.get( Params.depthwiseFilterHeight ); }
get bBias() { return this.parameterMapModified.get( Params.bBias ); }
get nActivationId() { return this.parameterMapModified.get( Params.nActivationId ); }
get nActivationId() { return Params.nActivationId.getStringOfValue( this.nActivationId ); }
get nActivationIdAtBlockEndId() { return this.parameterMapModified.get( Params.nActivationIdAtBlockEnd ); }
get nActivationIdAtBlockEndName() { return Params.nActivationIdAtBlockEnd.getStringOfValue( this.nActivationIdAtBlockEnd ); }
}
// Define parameter descriptions.
//!!! (2021/04/10 Remarked) They can not be evolved.
// Params.sourceHeight = new ParamDesc.Int( "sourceHeight", 1, ( 10 * 1024 ) );
// Params.sourceWidth = new ParamDesc.Int( "sourceWidth", 1, ( 10 * 1024 ) );
// Params.sourceChannelCount = new ParamDesc.Int( "sourceChannelCount", 1, ( 10 * 1024 ) );
Params.stepCountPerBlock = new ParamDesc.Int( "stepCountPerBlock", 0, ( 10 * 1024 ) );
Params.bChannelShuffler = new ParamDesc.Bool( "bChannelShuffler" );
Params.pointwise1ChannelCountRate = new ParamDesc.Int( "pointwise1ChannelCountRate", 1, 2 );
Params.depthwiseChannelMultiplierStep0 = new ParamDesc.AvgMax_Or_ChannelMultiplier( "depthwiseChannelMultiplierStep0" );
Params.depthwiseFilterHeight = new ParamDesc.Int( "depthwiseFilterHeight", 1, 9 );
Params.bBias = new ParamDesc.Bool( "bBias" );
Params.nActivationId = new ParamDesc.ActivationFunction( "nActivationId" );
Params.nActivationIdAtBlockEnd = new ParamDesc.ActivationFunction( "nActivationIdAtBlockEnd" );
/**
* Implement a block of ( depthwise convolution and pointwise convolution ) or ShuffleNetV2 (with 2 output channel groups) or MobileNetV1
* or MobileNetV2.
*
*
* @member {function} apply_and_destroy_or_keep
* This is a method. It has an parameter inputTensor (tf.tensor3d) represents the image ( height x width x channel ) which
* will be processed. It returns a new tf.tensor3d. All other tensors will be disposed. But inputTensor could be kept
* (if ( bKeepInputTensor == true ) ) or disposed (if ( bKeepInputTensor == false ) ). In fact, this method calls one of
* apply_and_destroy_or_keep_NotChannelShuffle_NotAddInputToOutput(), apply_and_destroy_or_keep_ChannelShuffle(),
* apply_and_destroy_or_keep_AddInputToOutput() according to the init()'s parameters.
*
* @member {number} outputChannelCount
* The output channel count of this block's last step.
*
* @member {PointDepthPoint.Base} step0
* The first step computation of this block.
*
* @member {PointDepthPoint.Base} stepLast
* The last step computation of this block. It may be the same as this.step0 when there is only one step inside this block.
*
* @see ChannelShuffler.ConcatPointwiseConv
*/
class Base {
/**
* Generator for initializing this object.
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* Some new progressToAdvance will be created and added to progressParent. The created progressToAdvance will be
* increased when every time advanced. The progressParent.getRoot() will be returned when every time yield.
*
* @param {Float32Array} inputFloat32Array
* A Float32Array whose values will be interpreted as weights.
*
* @param {number} byteOffsetBegin
* The position to start to decode from the inputFloat32Array. This is relative to the inputFloat32Array.buffer
* (not to the inputFloat32Array.byteOffset).
*
* @param {number} sourceHeight
* The height of the source image which will be processed by apply_and_destroy_or_keep(). This should always be specified and can
* not be null (i.e. it will never be extracted from inputFloat32Array and never by evolution).
*
* @param {number} sourceWidth
* The width of the source image which will be processed by apply_and_destroy_or_keep().c This should always be specified and can
* not be null (i.e. it will never be extracted from inputFloat32Array and never by evolution).
*
* @param {number} sourceChannelCount
* The channel count of the source image. It may be the output channel count of the previous convolution block, so it could be large.
* This should always be specified and can not be null (i.e. it will never be extracted from inputFloat32Array and never by evolution).
*
* @param {number} stepCountPerBlock
* There are how many step inside this block. If null, it will be extracted from inputFloat32Array (i.e. by evolution). If zero or
* negative (<= 0), every block will use only one tf.depthwiseConv2d( strides = 1, pad = "valid" ) for shrinking sourceHeight
* (minus ( filterHeight - 1 )). If positive (>= 1), every block will use one tf.depthwiseConv2d( strides = 2, pad = "same" ) to shrink
* (halve height x width) and use ( stepCountPerBlock - 1 ) times tf.depthwiseConv2d( strides = 1, pad = "same" ) until the block end.
*
* @param {boolean} bChannelShuffler
* If true, will like ShuffleNetV2 (i.e. split and concat channels). If false, will like MobileNetV1 or MobileNetV2 (i.e. add input
* to output). If null, it will be extracted from inputFloat32Array (i.e. by evolution). If ( stepCountPerBlock <= 0 ), this flag
* will be ignored.
*
* @param {number} pointwise1ChannelCountRate
* The first 1x1 pointwise convolution output channel count over of the second 1x1 pointwise convolution output channel count.
* That is, pointwise1ChannelCount = ( pointwise2ChannelCount * pointwise1ChannelCountRate ). If null, it will be extracted from
* inputFloat32Array (i.e. by evolution).
* - If ( stepCountPerBlock <= 0 ), this rate will be ignored because there will be no first 1x1 pointwise.
* - If ( bChannelShuffler == true ) and ( pointwise1ChannelCountRate == 1 ), will like ShuffleNetV2.
* - If ( bChannelShuffler == false ) and ( pointwise1ChannelCountRate == 1 ), will like MobileNetV1.
* - If ( bChannelShuffler == false ) and ( pointwise1ChannelCountRate > 1 ), will like MobileNetV2.
*
//!!! ...unfinished...
* @param {number} depthwiseChannelMultiplierStep0
* The depthwise convolution of the first step (Step 0) will expand input channel by this factor. If null, it will be extracted
* from inputFloat32Array (i.e. by evolution). If non-null, it should be integer between [ -2, 32 ]:
* - Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.AVG (-2): average pooling.
* - Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.MAX (-1): max pooling.
* - Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.NONE (0): this will be adjusted to 1 forcibly (always needs depthwise operation).
* - positive integer between [ 1, 32 ]: depthwise convolution and the number indicates channel multiplier.
*
* @param {boolean} bBias
* If true, there will be a bias after every convolution. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
*
* @param {string} nActivationId
* The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) after the convolution. If null, it will be extracted
* from inputFloat32Array (i.e. by evolution).
*
* @param {string} nActivationIdAtBlockEnd
* The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) after the convolution of the last PointDepthPoint's
* pointwise2ActivationId of this block. If null, it will be extracted from inputFloat32Array (i.e. by evolution). If the output of
* this block needs to be any arbitrary value, it is recommended not to use activation at the end of this block
* (i.e. nActivationIdAtBlockEnd == ValueDesc.ActivationFunction.Singleton.Ids.NONE) so that it will not be restricted by the range
* of the activation function.
*
//!!! ...unfinished...
//!!! ...unfinished... (2021/04/09) How to know now is MobileNetV2 (not MobileNetV1)? Maybe according to ( pointwise1ChannelCountRate > 1 )?
// Since pointwise2ActivationId is always NONE in MobileNetV2 (i.e. ( bChannelShuffler == false ), the nActivationIdAtBlockEnd is never used in MobileNetV2.
*
* @param {boolean} bKeepInputTensor
* If true, apply_and_destroy_or_keep() will not dispose inputTensor (i.e. keep). If it is null, it will be viewed as falsy
* (i.e. it will never be extracted from inputFloat32Array and never by evolution).
*
* @yield {ValueMax.Percentage.Aggregate}
* Yield ( value = progressParent.getRoot() ) when ( done = false ).
*
* @yield {boolean}
* Yield ( value = true ) when ( done = true ) successfully.
* Yield ( value = false ) when ( done = true ) failed.
*
* @see PointDepthPoint.Base.initer()
*/
* initer(
progressParent,
inputFloat32Array, byteOffsetBegin,
sourceHeight, sourceWidth, sourceChannelCount,
stepCountPerBlock,
bChannelShuffler,
pointwise1ChannelCountRate,
depthwiseChannelMultiplierStep0, depthwiseFilterHeight,
bBias, nActivationId, nActivationIdAtBlockEnd,
bKeepInputTensor
) {
// Both MobileNetV3 and ShuffleNetV2:
// - They all do not use (depthwise convolution) channelMultiplier.
// - They all use 1x1 (pointwise) convolution to expand channel count.
// - They all use 1x1 (pointwise) convolution before depthwise convolution.
// - They all use activation function after first pointwise convolution.
// - They all use depthwise convolution with ( pad = "same" ).
// - They all use depthwise convolution with ( strides = 2 ) for shrinking (halving) height x width.
// - They all do not use bias after pointwise and depthwise convolution.
//
// Inisde one of their block, three convolutions are used:
// A) 1x1 (pointwise) convolution, with activation.
// B) depthwise convolution, (ShuffleNetV2) without or (MobileNetV2) with activation.
// C) 1x1 (pointwise) convolution, (ShuffleNetV2) with or (MobileNetV2) without activation.
//
// In MobileNetV3, convolution A expands channel count (with activation), convolution C shrinks channel count (without activation).
// It may use squeeze-and-excitation after convolution B (without activation). When there is necessary to increase output channel
// count (usually in step 0 of a block), the convolution C is responsible for this.
//
// In ShuffleNetV2, convolution A (with activation), convolution B (without activation) and convolution C (with activation) never
// change channel count. When there is necessary to increase output channel count (usually in step 0 of a block), it expands channel
// count by concatenating two shrinked (halven) height x width.
// 0. Prepare
//!!! ...unfinished...
// Estimate the maximum value of progress.
let progressMax =
1 // for extracting parameters from inputFloat32Array.
+ 1 // for extracting pointwise1 filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for extracting depthwise filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for extracting pointwise2 filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for all pointwise1-depthwise-pointwise2 filters (and biases) ready.
;
let progressRoot = progressParent.getRoot();
let progressToAdvance = progressParent.addChild( new ValueMax.Percentage.Concrete( progressMax ) );
this.disposeTensors();
this.nextByteOffsetBegin = byteOffsetBegin;
this.sourceHeight = sourceHeight;
this.sourceWidth = sourceWidth;
this.sourceChannelCount = sourceChannelCount;
//!!! ...unfinished...
// 1. Extract parameters.
this.params = new Params();
let bParamsInitOk
= this.params.init( inputFloat32Array, byteOffsetBegin,
pointwise1ChannelCount, bPointwise1Bias, pointwise1ActivationId,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, bDepthwiseBias, depthwiseActivationId,
pointwise2ChannelCount, bPointwise2Bias, pointwise2ActivationId,
bAddInputToOutput );
if ( !bParamsInitOk )
return false; // e.g. input array does not have enough data.
this.nextByteOffsetBegin = this.params.defaultByteOffsetEnd;
//!!! ...unfinished...
// Get parameters' real (adjusted) values.
{
pointwise1ChannelCount = this.pointwise1ChannelCount;
bPointwise1Bias = this.bPointwise1Bias;
pointwise1ActivationId = this.pointwise1ActivationId;
depthwise_AvgMax_Or_ChannelMultiplier = this.depthwise_AvgMax_Or_ChannelMultiplier;
depthwiseFilterHeight = this.depthwiseFilterHeight;
depthwiseStridesPad = this.depthwiseStridesPad;
bDepthwiseBias = this.bDepthwiseBias;
depthwiseActivationId = this.depthwiseActivationId;
pointwise2ChannelCount = this.pointwise2ChannelCount;
bPointwise2Bias = this.bPointwise2Bias;
pointwise2ActivationId = this.pointwise2ActivationId;
bAddInputToOutput = this.bAddInputToOutput;
}
++progressToAdvance.value;
yield progressRoot; // Parameters extracted. Report progress.
this.stepCountPerBlock = stepCountPerBlock;
//!!! ...unfinished... (2021/04/10)
// Perhaps, Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.NONE (0) (no depthwise operation) could be viewed as ( bChannelShuffler == true ).
// Because it is not possible to change depthwiseChannelMultiplier in ShuffleNetV2 (it is always ( depthwiseChannelMultiplier == 1 )).
// (WRONG! it is possible to change depthwiseChannelMultiplier in ShuffleNetV2.)
// This could also reduce one parameter (drop the bChannelShuffler parameter).
this.bChannelShuffler = bChannelShuffler;
this.pointwise1ChannelCountRate = pointwise1ChannelCountRate;
//!!! ...unfinished... (2021/04/10) Place this adjustment after Params.init().
// The depthwise channel multipler of the step 0 can not be Params.depthwiseChannelMultiplierStep0.valueDesc.Ids.NONE (0).
// Otherwise, the input image will not be shrinked a little (for ( stepCountPerBlock <= 0 )) or will not be halven
// (for ( stepCountPerBlock >= 1 ). So force to 1 at least (always needs depthwise operation).
if ( depthwiseChannelMultiplierStep0 == 0 )
depthwiseChannelMultiplierStep0 = 1;
this.depthwiseChannelMultiplierStep0 = depthwiseChannelMultiplierStep0;
let depthwiseFilterWidth = depthwiseFilterHeight; // Assume depthwise filter's width equals its height.
this.depthwiseFilterHeight = depthwiseFilterHeight;
this.depthwiseFilterWidth = depthwiseFilterWidth;
this.bBias = bBias;
this.nActivationId = nActivationId;
this.nActivationIdAtBlockEnd = nActivationIdAtBlockEnd;
this.bKeepInputTensor = bKeepInputTensor;
this.bAddInputToOutput = !bChannelShuffler; // ChannelShuffler or AddInputToOutput, but not both. They are all for achieving skip connection.
let pointwise1Bias = bBias;
let pointwise1ActivationId = nActivationId;
let depthwiseBias = bBias;
let depthwiseActivationId = nActivationId;
let pointwise2Bias = bBias;
let pointwise2ActivationId = nActivationId;
if ( stepCountPerBlock <= 0 ) { // Not ShuffleNetV2, Not MobileNetV2.
// Only one step (i.e. step 0 ) for depthwise operation with ( strides = 1, pad = "valid" )
// for shrinking sourceHeight (minus ( filterHeight - 1 )).
let pointwise1ChannelCount = 0; // no pointwise convolution before depthwise convolution.
let pointwise2ChannelCount;
let depthwise_AvgMax_Or_ChannelMultiplier = depthwiseChannelMultiplierStep0; // (Can not be zero.)
if ( depthwise_AvgMax_Or_ChannelMultiplier > 0 ) { // Depthwise convolution.
pointwise2ChannelCount = sourceChannelCount * depthwiseChannelMultiplierStep0;
} else { // Avg pooling, or Max pooling.
pointwise2ChannelCount = sourceChannelCount; // The output channel count of average (or max) pooling is the same as input channel count.
}
let depthwiseStridesPad = 0; // ( depthwiseStrides == 1 ) and ( depthwisePad == "valid" ) so that shrinking sourceHeight a little.
// This is the last step of this block (i.e. at-block-end) because ( stepCountPerBlock <= 0 ) means there is only one step inside
// this block. And a different activation function may be used after pointwise2 convolution.
pointwise2ActivationId = nActivationIdAtBlockEnd;
let step0 = this.step0 = new PointDepthPoint.Base();
step0.init(
sourceChannelCount,
pointwise1ChannelCount, pointwise1Bias, pointwise1ActivationId,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, depthwiseBias, depthwiseActivationId,
pointwise2ChannelCount, pointwise2Bias, pointwise2ActivationId,
false, // It is not possible to add-input-to-output, because ( depthwisePad == "valid" ).
bKeepInputTensor // Step 0 may or may not keep input tensor according to caller's necessary.
);
this.stepLast = step0;
this.apply_and_destroy_or_keep = Base.apply_and_destroy_or_keep_NotChannelShuffle_NotAddInputToOutput;
this.outputChannelCount = step0.outputChannelCount;
} else { // ShuffleNetV2, or MobileNetV2.
// Step 0.
//
// The special points of a block's step 0 are:
// - halve the height x width. (Both ShuffleNetV2 and MobileNetV2) (by depthwise convolution with strides = 2)
// - Double channels. (By concat if ShuffleNetV2. By second pointwise if MobileNetV2.)
// - Expand channels by channelMultiplier of depthwise convolution. (Both ShuffleNetV2 and MobileNetV2 do not have this. It is added by us.)
let step0, step0Branch;
{
let depthwise_AvgMax_Or_ChannelMultiplier = depthwiseChannelMultiplierStep0; // (Can not be zero.)
// Step 0 is responsibile for halving input's height (and width).
let depthwiseStridesPad = 2; // ( depthwiseStrides == 2 ) and ( depthwisePad == "same" )
let pointwise1ChannelCount, pointwise2ChannelCount;
if ( bChannelShuffler ) { // ShuffleNetV2.
pointwise2ChannelCount = sourceChannelCount * 1; // In ShuffleNetV2, all convolutions do not change channel count
// If an operation has no activation function, it can have no bias too. Because the next operation's bias can achieve the same result.
depthwiseBias = false;
// In ShuffleNetV2, depthwise convolution does not have activation function.
depthwiseActivationId = PointDepthPoint.Params.Activation.Ids.NONE;
} else { // MobileNetV1, or MobileNetV2.
pointwise2ChannelCount = sourceChannelCount * 2; // The output channel count of step 0 of MobileNetV2 is twice as input.
// If an operation has no activation function, it can have no bias too. Because the next operation's bias can achieve the same result.
pointwise2Bias = false;
//!!! ...unfinished... (2021/04/09) How to know now is MobileNetV2 (not MobileNetV1)? Maybe according to ( pointwise1ChannelCountRate > 1 )?
// In MobileNetV2, the second 1x1 pointwise convolution does not have activation function in default.
//
// But it could be changed by nActivationIdAtBlockEnd for the last step of the block.
pointwise2ActivationId = PointDepthPoint.Params.Activation.Ids.NONE;
}
// If there is only one step, this (step 0) is also the last step of this block (i.e. at-block-end) and a different activation
// function may be used after pointwise2 convolution.
//
// Even if in MobileNetV2 (pointwise2 convolution does not have activation function in default), this is still true.
if ( 1 == stepCountPerBlock ) {
pointwise2ActivationId = nActivationIdAtBlockEnd;
}
// If ( pointwise1ChannelCount < pointwise2ChannelCount ), similiar to ResNet.
// If ( pointwise1ChannelCount == pointwise2ChannelCount ), similiar to MobileNetV1 or ShufffleNetV2.
// If ( pointwise1ChannelCount > pointwise2ChannelCount ), similiar to MobileNetV2.
pointwise1ChannelCount = pointwise2ChannelCount * pointwise1ChannelCountRate;
step0 = this.step0 = new PointDepthPoint.Base();
step0.init(
sourceChannelCount,
pointwise1ChannelCount, pointwise1Bias, pointwise1ActivationId,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, depthwiseBias, depthwiseActivationId,
pointwise2ChannelCount, pointwise2Bias, pointwise2ActivationId,
// In MobileNet2, step 0 is not possible, because output channel count is tiwce as input.
// In ShuffleNetV2, the skipping connection is achieved by concatenating.
// So, it is not necessary to add input to output.
false,
bKeepInputTensor // Step 0 may or may not keep input tensor according to caller's necessary.
);
// Step0's branch (ShuffleNetV2)
//
// The step 0 of ShuffleNetV2 has a branch which also halves the height and width by depthwise convolution. And it does not have
// the first 1x1 (pointwise) convolution. But it has the second 1x1 (pointwise) convolution.
if ( bChannelShuffler ) {
this.step0Branch = step0Branch = new PointDepthPoint.Base();
step0Branch.init(
sourceChannelCount,
// ShuffleNetV2 Step0's branch does not have the first 1x1 pointwise convolution before depthwise convolution ( strides = 2 ).
0, false, ValueDesc.ActivationFunction.Singleton.Ids.NONE,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, depthwiseBias, depthwiseActivationId,
pointwise2ChannelCount, pointwise2Bias, pointwise2ActivationId,
false, // In ShuffleNetV2, the skipping connection is achieved by concatenating. So, it is not necessary to add input to output.
true // This is the only case that must keep input tensor, because the input tensor need be re-used by the main path of setp 0.
);
// Pre-allocated array (with only two elements) for improving performance by reducing memory re-allocation.
this.concatTensorArray = new Array( 2 );
// Bind in step 0's logic, because step 1 (2, 3, ...) may not existed.
this.apply_and_destroy_or_keep = Base.apply_and_destroy_or_keep_ChannelShuffle;
this.outputChannelCount = step0.outputChannelCount + step0Branch.outputChannelCount;
} else {
// Bind in step 0's logic, because step 1 (2, 3, ...) may not existed.
this.apply_and_destroy_or_keep = Base.apply_and_destroy_or_keep_AddInputToOutput;
this.outputChannelCount = step0.outputChannelCount;
}
}
// Step 1, 2, 3, ...
if ( stepCountPerBlock > 0 ) {
let depthwise_AvgMax_Or_ChannelMultiplier = depthwiseChannelMultiplierStep0;
if ( depthwise_AvgMax_Or_ChannelMultiplier >= 0 ) { // Depthwise convolution.
// In non-step0, it should not expand channel. Only step 0 can have ( channelMultiplier > 1 ). So, force to 1.
depthwise_AvgMax_Or_ChannelMultiplier = 1;
} else { // Avg pooling, or Max pooling.
// Do nothing. Keep going.
}
// Force to ( depthwiseStrides == 1 ), because only step 0 (i.e. not here) should halve input's height (and width).
let depthwiseStridesPad = 1; // ( depthwiseStrides == 1 ) and ( depthwisePad == "same" )
// In ShuffleNetV2, the input channel count of step 1 (2, 3, ...) is the concatenated output channel count of the
// main and branch of step 0. However, they will be splitted (by channel shuffler) into two channel groups. So every
// channel group has just only half of concatenated channel count of step 0 (i.e. not including the step0Branch).
//
// In MobileNetV2, the input channel count of step 1 (2, 3, ...) is the output channel count of the step 0.
//
// In a word, they are all the same as step0.outputChannelCount.
let channelCount_pointwise1Before = step0.outputChannelCount;
let pointwise2ChannelCount = channelCount_pointwise1Before; // Every step will output the same channel count as input.
// The first 1x1 pointwise convolution can change channel count.
let pointwise1ChannelCount = pointwise2ChannelCount * pointwise1ChannelCountRate;
// In ShuffleNetV2, there is a channel shuffler in every step (except setp 0). It is shared by these steps in the same block.
if ( bChannelShuffler ) {
let concatenatedChannelCount = step0.outputChannelCount + step0Branch.outputChannelCount;
let sourceConcatenatedShape = this.sourceConcatenatedShape = [ sourceHeight, sourceWidth, concatenatedChannelCount ];
let outputGroupCount = 2; // ShuffleNetV2 always uses two (depthwise convolution) groups.
//!!! (2021/04/10) ...unfinished... Using ChannelShuffler.ConcatPointwiseConv instead.
this.concatGather = new ChannelShuffler.ConcatGather();
this.concatGather.init( sourceConcatenatedShape, outputGroupCount );
this.concatPointwiseConv = new ChannelShuffler.ConcatPointwiseConv();
this.concatPointwiseConv.init( sourceConcatenatedShape, outputGroupCount );
}
this.steps1After = new Array( stepCountPerBlock - 1 ); // "- 1" because this array does not include step0.
for ( let i = 0; i < this.steps1After.length; ++i ) {
// If this is the last step of this block (i.e. at-block-end), a different activation function may be used after
// pointwise2 convolution.
//
// Even if in MobileNetV2 (pointwise2 convolution does not have activation function in default), this is still true.
if ( i == ( this.steps1After.length - 1 ) ) {
pointwise2ActivationId = nActivationIdAtBlockEnd;
}
let step = new PointDepthPoint.Base();
step.init(
channelCount_pointwise1Before,
pointwise1ChannelCount, pointwise1Bias, pointwise1ActivationId,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, depthwiseBias, depthwiseActivationId,
pointwise2ChannelCount, pointwise2Bias, pointwise2ActivationId,
this.bAddInputToOutput,
false // No matter bKeepInputTensor, all steps (except step 0) should not keep input tensor.
);
this.steps1After[ i ] = step;
}
if ( 1 == stepCountPerBlock ) {
this.stepLast = this.step0; // If there is only one step, it is also the last step.
} else {
this.stepLast = this.steps1After[ this.steps1After.length - 1 ]; // Shortcut to the last step.
}
}
}
}
/**
* Initialize this object by calling initer() and advance the generator by loop until done.
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* If null, a temporary progress object will be created.
*
* @return {boolean}
* Return true if successfully (and progressParent.valuePercentage will be equal to 100).
* Return false if failed (and progressParent.valuePercentage will be less than 100).
*
* @see PointDepthPoint.Base.init()
*/
init(
progressParent,
inputFloat32Array, byteOffsetBegin,
sourceHeight, sourceWidth, sourceChannelCount,
stepCountPerBlock,
bChannelShuffler,
pointwise1ChannelCountRate,
depthwiseChannelMultiplierStep0, depthwiseFilterHeight, bBias, nActivationId, nActivationIdAtBlockEnd,
bKeepInputTensor
) {
progressParent = progressParent || ( new ValueMax.Percentage.Aggregate() );
let initer = this.initer(
progressParent,
inputFloat32Array, byteOffsetBegin,
sourceHeight, sourceWidth, sourceChannelCount,
stepCountPerBlock,
bChannelShuffler,
pointwise1ChannelCountRate,
depthwiseChannelMultiplierStep0, depthwiseFilterHeight, bBias, nActivationId, nActivationIdAtBlockEnd,
bKeepInputTensor
);
let initerNext;
do {
initerNext = initer.next();
} while ( ! initerNext.done ); // When ( false == initerNext.done ), the ( initerNext.value ) will be progressParent.getRoot().
let bInitOk = initerNext.value; // When ( true == initerNext.done ), the ( initerNext.value ) will be initialization successfully or failed.
return bInitOk;
}
disposeTensors() {
//!!! (2021/04/10) ...unfinished... Using ChannelShuffler.ConcatPointwiseConv instead.
if ( this.concatGather ) {
this.concatGather.disposeTensors();
this.concatGather = null;
}
if ( this.concatPointwiseConv ) {
this.concatPointwiseConv.disposeTensors();
this.concatPointwiseConv = null;
}
if ( this.concatTensorArray ) {
this.concatTensorArray = null;
}
if ( this.step0 ) {
this.step0.disposeTensors();
this.step0 = null;
}
if ( this.step0Branch ) {
this.step0Branch.disposeTensors();
this.step0Branch = null;
}
if ( this.steps1After ) {
for ( let step of this.steps1After ) {
step.disposeTensors();
}
this.steps1After = null;
}
this.stepLast = null; // It has already de disposed by this.step0 or this.steps1After.
}
/** Process input, destroy input, return result. (For Not ShuffleNetV2 and Not MobileNetV2.)
*
* @param {Block} this
* This method should not be called directly. It should be called by calling apply_and_destroy_or_keep().
*
* @param {tf.tensor3d} inputTensor
* The image which will be processed. This inputTensor may or may not be disposed according to init()'s bKeepInputTensor.
*
* @return {tf.tensor3d} Return a new tensor. All other intermediate tensors were disposed.
*/
static apply_and_destroy_or_keep_NotChannelShuffle_NotAddInputToOutput( inputTensor ) {
return this.step0.apply_and_destroy_or_keep( inputTensor );
}
//!!! ...unfinished... (2021/04/13) (Our) Adjusted ShuffleNetV2:
//
// Since channel shuffler could achieved efficiently by pointwise convolution, it may be possible to combine the pointwise2
// convolution (after depthwise convolution) and the pointwise convolution (of channel shuffler). That is:
// - Concatenate the output of depthwise convolution and the other output group.
// - Pointwise convolution to generate output group 1.
// - Pointwise convolution to generate output group 2.
//
// In order to achieve it, there is a pre-condition: the pointwise2 convolution (after depthwise convolution) do not
// have bias and activation function. The reason is that the channel shuffler (achieved by pointwise convolution) uses
// only pointwise convolution without bias and activation function.
//
//
// If the poitwise1 convolution (of every step (include step 0 too)) could be discarded, the step 0 and step 0's branch could
// be achieved simultaneously by:
// - once depthwise convolution (channelMultipler = 2, strides = 2, pad = same, bias, COS).
// - concat.
// - twice pointwise2 convolution (no bias, no activation function).
//
// Note that the depthwise convolution (channelMultipler = 2, strides = 2) combines two depthwise convolution
// (channelMultipler = 1, strides = 2) of step 0 and step 0's branch. So, it is one less depthwise convolution.
//
//
// And, the step 1 (, 2, 3, ...) could be achieved by:
// - once depthwise convolution (channelMultipler = 1, strides = 1, pad = same, bias, COS).
// - concat.
// - twice pointwise2 convolution (no bias, no activation function).
//
// Note that the twice pointwise2 convolution (no bias, no activation function) achieves not only pointwise convolution but
// also channel shuffler. So, it is one less one pointwise convolution.
//
/** Process input, destroy input, return result. (For ShuffleNetV2.)
*
* @param {Block} this
* This method should not be called directly. It should be called by calling apply_and_destroy_or_keep().
*
* @param {tf.tensor3d} inputTensor
* The image which will be processed. This inputTensor may or may not be disposed according to init()'s bKeepInputTensor.
*
* @return {tf.tensor3d} Return a new tensor. All other intermediate tensors were disposed.
*/
static apply_and_destroy_or_keep_ChannelShuffle( inputTensor ) {
// Keep data as local variables for improving performance.
//!!! ...unfinished... Compare performance to call concatGather.concatGather() directly.
//!!! (2021/04/08) ...unfinished... Using ChannelShuffler.ConcatPointwiseConv instead.
let lastAxisId = this.concatGather.shuffleInfo.lastAxisId;
// There are exactly two output channel groups, take them out from array. (for reducing array access cost.)
let group0_channelIndicesTensor1d = this.concatGather.shuffledChannelIndicesTensor1dArray[ 0 ];
let group1_channelIndicesTensor1d = this.concatGather.shuffledChannelIndicesTensor1dArray[ 1 ];
let concatTensorArray = this.concatTensorArray; // Keep pre-allocated array (with two elements) as local variables for improving performance.
// tensor of convolution group 0, tensor of convolution group 1, new tensor of convolution group 1, tensor of concatenation of group 0 and 1.
let t0, t1, t1New, concatenatedTensor;
// Step 0.
concatTensorArray[ 0 ] = t0 = this.step0Branch.apply_and_destroy_or_keep( inputTensor ); // Branch (will NOT destroy input tensor).
concatTensorArray[ 1 ] = t1 = this.step0 .apply_and_destroy_or_keep( inputTensor ); // Main Path (may or may not destroy input tensor).
concatenatedTensor = tf.concat( concatTensorArray, lastAxisId );
t0.dispose(); // Dispose all intermediate (temporary) data.
t1.dispose(); // Dispose all intermediate (temporary) data.
// Step 1, 2, 3, ...
let step;
for ( let i = 0; i < this.steps1After.length; ++i ) {
step = this.steps1After[ i ];
// shuffle and split by gather (one operation achieves two operations).
t0 = concatenatedTensor.gather( group0_channelIndicesTensor1d, lastAxisId );
t1 = concatenatedTensor.gather( group1_channelIndicesTensor1d, lastAxisId );
concatenatedTensor.dispose(); // Dispose all intermediate (temporary) data.
concatTensorArray[ 0 ] = t0; // Branch do nothing (as a shortcut).
concatTensorArray[ 1 ] = t1New = step.apply_and_destroy_or_keep( t1 ); // Main path is processed.
concatenatedTensor = tf.concat( concatTensorArray, lastAxisId );
t0.dispose(); // Dispose all intermediate (temporary) data.
t1New.dispose(); // Dispose all intermediate (temporary) data.
}
return concatenatedTensor;
}
/** Process input, destroy input, return result. (For MobileNetV2.)
*
* @param {Block} this
* This method should not be called directly. It should be called by calling apply_and_destroy_or_keep().
*
* @param {tf.tensor3d} inputTensor
* The image which will be processed. This inputTensor may or may not be disposed according to init()'s bKeepInputTensor.
*
* @return {tf.tensor3d} Return a new tensor. All other intermediate tensors were disposed.
*/
static apply_and_destroy_or_keep_AddInputToOutput( inputTensor ) {
let t, tNew;
// Step 0.
t = this.step0.apply_and_destroy_or_keep( inputTensor );
// Step 1, 2, 3, ...
let step;
for ( let i = 0; i < this.steps1After.length; ++i ) {
step = this.steps1After[ i ];
t = step.apply_and_destroy_or_keep( t );
}
return t;
}
}
| Update Block.js | CNN/Conv/Block.js | Update Block.js | <ide><path>NN/Conv/Block.js
<ide> // If the poitwise1 convolution (of every step (include step 0 too)) could be discarded, the step 0 and step 0's branch could
<ide> // be achieved simultaneously by:
<ide> // - once depthwise convolution (channelMultipler = 2, strides = 2, pad = same, bias, COS).
<del>// - concat.
<add>// - No need to concatenate because the above operation already double channel count.
<ide> // - twice pointwise2 convolution (no bias, no activation function).
<del>//
<del>// Note that the depthwise convolution (channelMultipler = 2, strides = 2) combines two depthwise convolution
<del>// (channelMultipler = 1, strides = 2) of step 0 and step 0's branch. So, it is one less depthwise convolution.
<del>//
<ide> //
<ide> // And, the step 1 (, 2, 3, ...) could be achieved by:
<ide> // - once depthwise convolution (channelMultipler = 1, strides = 1, pad = same, bias, COS).
<del>// - concat.
<add>// - concatenate.
<ide> // - twice pointwise2 convolution (no bias, no activation function).
<ide> //
<del>// Note that the twice pointwise2 convolution (no bias, no activation function) achieves not only pointwise convolution but
<del>// also channel shuffler. So, it is one less one pointwise convolution.
<add>// And, the last step of the block could be achieved by:
<add>// - once depthwise convolution (channelMultipler = 1, strides = 1, pad = same, bias, COS).
<add>// - concatenate.
<add>// - once pointwise2 convolution (no bias, no activation function).
<add>//
<add>// Note that:
<add>// - The depthwise convolution (channelMultipler = 2, strides = 2) of step 0 achieves simultaneously two depthwise
<add>// convolution (channelMultipler = 1, strides = 2) of step 0 and step 0's branch. So, it is one less depthwise
<add>// convolution, and one less concatenating.
<add>//
<add>// - The twice pointwise2 convolution (no bias, no activation function) achieves not only pointwise convolution but
<add>// also channel shuffling. So, it is one less pointwise convolution.
<add>//
<add>// - The once pointwise2 convolution (no bias, no activation function) of last step achieves simultaneously pointwise
<add>// convolution, channel shuffling, and concatenating. So, it is not only one less pointwise convolution, but also
<add>// one less concatenating.
<ide> //
<ide>
<ide> /** Process input, destroy input, return result. (For ShuffleNetV2.) |
|
Java | lgpl-2.1 | 18e1ce3bc231ec8f34f9358e4ba3dbf50cff9452 | 0 | lopescan/languagetool,janissl/languagetool,languagetool-org/languagetool,meg0man/languagetool,languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool,lopescan/languagetool,meg0man/languagetool,lopescan/languagetool,lopescan/languagetool,janissl/languagetool,languagetool-org/languagetool,janissl/languagetool,meg0man/languagetool,jimregan/languagetool,lopescan/languagetool,janissl/languagetool,jimregan/languagetool,janissl/languagetool,meg0man/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,meg0man/languagetool,janissl/languagetool,jimregan/languagetool | /* LanguageTool, a natural language style checker
* Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de)
*
* 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 St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.server;
import org.languagetool.JLanguageTool;
import org.languagetool.rules.RuleMatch;
import java.util.List;
import static org.languagetool.tools.StringTools.escapeXML;
/**
* Return LanguageTool matches in the same XML format as After The Deadline.
* See the <a href="http://www.afterthedeadline.com/api.slp">AtD API documentation</a>.
* @since 2.7
*/
public class AtDXmlSerializer {
public String ruleMatchesToXml(List<RuleMatch> matches, String text) {
StringBuilder sb = new StringBuilder();
sb.append("<results>\n");
sb.append("<!-- Server: LanguageTool " + JLanguageTool.VERSION + " (" + JLanguageTool.BUILD_DATE + ") -->\n");
for (RuleMatch match : matches) {
addRuleMatch(sb, match, text);
}
sb.append("</results>\n");
return sb.toString();
}
private void addRuleMatch(StringBuilder sb, RuleMatch match, String text) {
String errorText = text.substring(match.getFromPos(), match.getToPos());
if (errorText.contains("(") || errorText.contains(")")) {
// these matches need to be removed, they seem to confuse the client
// so that no matches at all get shown...
return;
}
sb.append(" <error>\n");
sb.append(" <string>").append(escapeXML(errorText)).append("</string>\n");
String cleanMessage = match.getShortMessage() != null ?
match.getShortMessage() : match.getMessage().replace("<suggestion>", "'").replace("</suggestion>", "'");
sb.append(" <description>").append(escapeXML(cleanMessage)).append("</description>\n");
String preContext = getPreContext(text, match.getFromPos());
if (preContext.isEmpty()) {
sb.append(" <precontext/>\n");
} else {
sb.append(" <precontext>").append(escapeXML(preContext)).append("</precontext>\n");
}
if (match.getSuggestedReplacements().size() > 0) {
sb.append(" <suggestions>\n");
for (String suggestion : match.getSuggestedReplacements()) {
sb.append(" <option>").append(escapeXML(suggestion)).append("</option>\n");
}
sb.append(" </suggestions>\n");
}
String type = match.getRule().isDictionaryBasedSpellingRule() ? "spelling" : "grammar";
sb.append(" <type>").append(escapeXML(type)).append("</type>\n");
// TODO: we return the URL of external pages here, but WordPress/Jetpack shows the page
// in a window that's too small, so we have to disable this very nice feature for now...
//if (rule.getUrl() != null) {
// sb.append(" <url>").append(escapeXML(rule.getUrl().toString())).append("</url>\n");
//}
sb.append(" </error>\n");
}
/** Get the context to the left of the given position. */
String getPreContext(String text, int fromPos) {
String preText = text.substring(0, fromPos);
String[] parts = preText.trim().split("\\s");
if (parts.length == 0) {
return "";
} else {
String lastPart = parts[parts.length-1];
// This seems a bit strange, but we (roughly) emulate AtD's behavior here. See AtD's error.slp.
if (lastPart.matches(".*[()\\[\\],;:/-].*")) {
return "";
} else {
return lastPart;
}
}
}
}
| languagetool-server/src/main/java/org/languagetool/server/AtDXmlSerializer.java | /* LanguageTool, a natural language style checker
* Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de)
*
* 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 St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.server;
import org.languagetool.rules.RuleMatch;
import java.util.List;
import static org.languagetool.tools.StringTools.escapeXML;
/**
* Return LanguageTool matches in the same XML format as After The Deadline.
* See the <a href="http://www.afterthedeadline.com/api.slp">AtD API documentation</a>.
* @since 2.7
*/
public class AtDXmlSerializer {
public String ruleMatchesToXml(List<RuleMatch> matches, String text) {
StringBuilder sb = new StringBuilder();
sb.append("<results>\n");
for (RuleMatch match : matches) {
addRuleMatch(sb, match, text);
}
sb.append("</results>\n");
return sb.toString();
}
private void addRuleMatch(StringBuilder sb, RuleMatch match, String text) {
String errorText = text.substring(match.getFromPos(), match.getToPos());
if (errorText.contains("(") || errorText.contains(")")) {
// these matches need to be removed, they seem to confuse the client
// so that no matches at all get shown...
return;
}
sb.append(" <error>\n");
sb.append(" <string>").append(escapeXML(errorText)).append("</string>\n");
String cleanMessage = match.getShortMessage() != null ?
match.getShortMessage() : match.getMessage().replace("<suggestion>", "'").replace("</suggestion>", "'");
sb.append(" <description>").append(escapeXML(cleanMessage)).append("</description>\n");
String preContext = getPreContext(text, match.getFromPos());
if (preContext.isEmpty()) {
sb.append(" <precontext/>\n");
} else {
sb.append(" <precontext>").append(escapeXML(preContext)).append("</precontext>\n");
}
if (match.getSuggestedReplacements().size() > 0) {
sb.append(" <suggestions>\n");
for (String suggestion : match.getSuggestedReplacements()) {
sb.append(" <option>").append(escapeXML(suggestion)).append("</option>\n");
}
sb.append(" </suggestions>\n");
}
String type = match.getRule().isDictionaryBasedSpellingRule() ? "spelling" : "grammar";
sb.append(" <type>").append(escapeXML(type)).append("</type>\n");
// TODO: we return the URL of external pages here, but WordPress/Jetpack shows the page
// in a window that's too small, so we have to disable this very nice feature for now...
//if (rule.getUrl() != null) {
// sb.append(" <url>").append(escapeXML(rule.getUrl().toString())).append("</url>\n");
//}
sb.append(" </error>\n");
}
/** Get the context to the left of the given position. */
String getPreContext(String text, int fromPos) {
String preText = text.substring(0, fromPos);
String[] parts = preText.trim().split("\\s");
if (parts.length == 0) {
return "";
} else {
String lastPart = parts[parts.length-1];
// This seems a bit strange, but we (roughly) emulate AtD's behavior here. See AtD's error.slp.
if (lastPart.matches(".*[()\\[\\],;:/-].*")) {
return "";
} else {
return lastPart;
}
}
}
}
| add LT version and build date to output as a comment
| languagetool-server/src/main/java/org/languagetool/server/AtDXmlSerializer.java | add LT version and build date to output as a comment | <ide><path>anguagetool-server/src/main/java/org/languagetool/server/AtDXmlSerializer.java
<ide> */
<ide> package org.languagetool.server;
<ide>
<add>import org.languagetool.JLanguageTool;
<ide> import org.languagetool.rules.RuleMatch;
<ide>
<ide> import java.util.List;
<ide> public String ruleMatchesToXml(List<RuleMatch> matches, String text) {
<ide> StringBuilder sb = new StringBuilder();
<ide> sb.append("<results>\n");
<add> sb.append("<!-- Server: LanguageTool " + JLanguageTool.VERSION + " (" + JLanguageTool.BUILD_DATE + ") -->\n");
<ide> for (RuleMatch match : matches) {
<ide> addRuleMatch(sb, match, text);
<ide> } |
|
Java | mit | 97dfbc880d6261f97e4af44d4d621cdae7ff8adc | 0 | rephormat/ripme,sleaze/ripme,rephormat/ripme,rephormat/ripme,sleaze/ripme,sleaze/ripme | package com.rarchives.ripme.ripper;
import java.awt.Desktop;
import java.io.*;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import com.rarchives.ripme.App;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.jsoup.HttpStatusException;
import com.rarchives.ripme.ui.RipStatusComplete;
import com.rarchives.ripme.ui.RipStatusHandler;
import com.rarchives.ripme.ui.RipStatusMessage;
import com.rarchives.ripme.ui.RipStatusMessage.STATUS;
import com.rarchives.ripme.utils.Utils;
import java.io.File;
import java.util.Scanner;
public abstract class AbstractRipper
extends Observable
implements RipperInterface, Runnable {
protected static final Logger LOGGER = Logger.getLogger(AbstractRipper.class);
private final String URLHistoryFile = Utils.getURLHistoryFile();
public static final String USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
protected URL url;
protected File workingDir;
DownloadThreadPool threadPool;
RipStatusHandler observer = null;
private boolean completed = true;
public abstract void rip() throws IOException;
public abstract String getHost();
public abstract String getGID(URL url) throws MalformedURLException;
public boolean hasASAPRipping() { return false; }
// Everytime addUrlToDownload skips a already downloaded url this increases by 1
public int alreadyDownloadedUrls = 0;
private boolean shouldStop = false;
private static boolean thisIsATest = false;
public void stop() {
shouldStop = true;
}
public boolean isStopped() {
return shouldStop;
}
protected void stopCheck() throws IOException {
if (shouldStop) {
throw new IOException("Ripping interrupted");
}
}
/**
* Adds a URL to the url history file
* @param downloadedURL URL to check if downloaded
*/
protected void writeDownloadedURL(String downloadedURL) throws IOException {
// If "save urls only" is checked don't write to the url history file
if (Utils.getConfigBoolean("urls_only.save", false)) {
return;
}
downloadedURL = normalizeUrl(downloadedURL);
BufferedWriter bw = null;
FileWriter fw = null;
try {
File file = new File(URLHistoryFile);
if (!new File(Utils.getConfigDir()).exists()) {
LOGGER.error("Config dir doesn't exist");
LOGGER.info("Making config dir");
boolean couldMakeDir = new File(Utils.getConfigDir()).mkdirs();
if (!couldMakeDir) {
LOGGER.error("Couldn't make config dir");
return;
}
}
// if file doesnt exists, then create it
if (!file.exists()) {
boolean couldMakeDir = file.createNewFile();
if (!couldMakeDir) {
LOGGER.error("Couldn't url history file");
return;
}
}
if (!file.canWrite()) {
LOGGER.error("Can't write to url history file: " + URLHistoryFile);
return;
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(downloadedURL);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* Normalize a URL
* @param url URL to check if downloaded
*/
public String normalizeUrl(String url) {
return url;
}
/**
* Checks to see if Ripme has already downloaded a URL
* @param url URL to check if downloaded
* @return
* Returns true if previously downloaded.
* Returns false if not yet downloaded.
*/
protected boolean hasDownloadedURL(String url) {
File file = new File(URLHistoryFile);
url = normalizeUrl(url);
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.equals(url)) {
return true;
}
}
} catch (FileNotFoundException e) {
return false;
}
return false;
}
/**
* Ensures inheriting ripper can rip this URL, raises exception if not.
* Otherwise initializes working directory and thread pool.
*
* @param url
* URL to rip.
* @throws IOException
* If anything goes wrong.
*/
public AbstractRipper(URL url) throws IOException {
if (!canRip(url)) {
throw new MalformedURLException("Unable to rip url: " + url);
}
this.url = sanitizeURL(url);
}
/**
* Sets ripper's:
* Working directory
* Logger (for debugging)
* FileAppender
* Threadpool
* @throws IOException
* Always be prepared.
*/
public void setup() throws IOException {
setWorkingDir(this.url);
Logger rootLogger = Logger.getRootLogger();
FileAppender fa = (FileAppender) rootLogger.getAppender("FILE");
if (fa != null) {
fa.setFile(this.workingDir + File.separator + "log.txt");
fa.activateOptions();
}
this.threadPool = new DownloadThreadPool();
}
public void setObserver(RipStatusHandler obs) {
this.observer = obs;
}
/**
* Queues image to be downloaded and saved.
* @param url
* URL of the file
* @param saveAs
* Path of the local file to save the content to.
* @return True on success, false on failure.
*/
public abstract boolean addURLToDownload(URL url, File saveAs);
/**
* Queues image to be downloaded and saved.
* @param url
* URL of the file
* @param saveAs
* Path of the local file to save the content to.
* @param referrer
* The HTTP referrer to use while downloading this file.
* @param cookies
* The cookies to send to the server while downloading this file.
* @return
* True if downloaded successfully
* False if failed to download
*/
protected abstract boolean addURLToDownload(URL url, File saveAs, String referrer, Map<String, String> cookies,
Boolean getFileExtFromMIME);
/**
* Queues image to be downloaded and saved.
* @param url
* URL of the file
* @param prefix
* Prefix for the downloaded file
* @param subdirectory
* Path to get to desired directory from working directory
* @param referrer
* The HTTP referrer to use while downloading this file.
* @param cookies
* The cookies to send to the server while downloading this file.
* @param fileName
* The name that file will be written to
* @return
* True if downloaded successfully
* False if failed to download
*/
protected boolean addURLToDownload(URL url, String prefix, String subdirectory, String referrer, Map<String, String> cookies, String fileName, String extension, Boolean getFileExtFromMIME) {
// Make sure the url doesn't contain any spaces as that can cause a 400 error when requesting the file
if (url.toExternalForm().contains(" ")) {
// If for some reason the url with all spaces encoded as %20 is malformed print an error
try {
url = new URL(url.toExternalForm().replaceAll(" ", "%20"));
} catch (MalformedURLException e) {
LOGGER.error("Unable to remove spaces from url\nURL: " + url.toExternalForm());
e.printStackTrace();
}
}
// Don't re-add the url if it was downloaded in a previous rip
if (Utils.getConfigBoolean("remember.url_history", true) && !isThisATest()) {
if (hasDownloadedURL(url.toExternalForm())) {
sendUpdate(STATUS.DOWNLOAD_WARN, "Already downloaded " + url.toExternalForm());
alreadyDownloadedUrls += 1;
return false;
}
}
try {
stopCheck();
} catch (IOException e) {
LOGGER.debug("Ripper has been stopped");
return false;
}
LOGGER.debug("url: " + url + ", prefix: " + prefix + ", subdirectory" + subdirectory + ", referrer: " + referrer + ", cookies: " + cookies + ", fileName: " + fileName);
String saveAs = getFileName(url, fileName, extension);
File saveFileAs;
try {
if (!subdirectory.equals("")) {
subdirectory = Utils.filesystemSafe(subdirectory);
subdirectory = File.separator + subdirectory;
}
prefix = Utils.filesystemSanitized(prefix);
String topFolderName = workingDir.getCanonicalPath();
if (App.stringToAppendToFoldername != null) {
topFolderName = topFolderName + App.stringToAppendToFoldername;
}
saveFileAs = new File(
topFolderName
+ subdirectory
+ File.separator
+ prefix
+ saveAs);
} catch (IOException e) {
LOGGER.error("[!] Error creating save file path for URL '" + url + "':", e);
return false;
}
LOGGER.debug("Downloading " + url + " to " + saveFileAs);
if (!saveFileAs.getParentFile().exists()) {
LOGGER.info("[+] Creating directory: " + Utils.removeCWD(saveFileAs.getParent()));
saveFileAs.getParentFile().mkdirs();
}
if (Utils.getConfigBoolean("remember.url_history", true) && !isThisATest()) {
LOGGER.info("Writing " + url.toExternalForm() + " to file");
try {
writeDownloadedURL(url.toExternalForm() + "\n");
} catch (IOException e) {
LOGGER.debug("Unable to write URL history file");
}
}
return addURLToDownload(url, saveFileAs, referrer, cookies, getFileExtFromMIME);
}
protected boolean addURLToDownload(URL url, String prefix, String subdirectory, String referrer, Map<String,String> cookies, String fileName, String extension) {
return addURLToDownload(url, prefix, subdirectory, referrer, cookies, fileName, extension, false);
}
protected boolean addURLToDownload(URL url, String prefix, String subdirectory, String referrer, Map<String, String> cookies, String fileName) {
return addURLToDownload(url, prefix, subdirectory, referrer, cookies, fileName, null);
}
/**
* Queues file to be downloaded and saved. With options.
* @param url
* URL to download.
* @param prefix
* Prefix to prepend to the saved filename.
* @param subdirectory
* Sub-directory of the working directory to save the images to.
* @return True on success, flase on failure.
*/
protected boolean addURLToDownload(URL url, String prefix, String subdirectory) {
return addURLToDownload(url, prefix, subdirectory, null, null, null);
}
protected boolean addURLToDownload(URL url, String prefix, String subdirectory, String referrer, Map<String, String> cookies) {
return addURLToDownload(url, prefix, subdirectory, referrer, cookies, null);
}
/**
* Queues image to be downloaded and saved.
* Uses filename from URL (and 'prefix') to decide filename.
* @param url
* URL to download
* @param prefix
* Text to append to saved filename.
* @return True on success, flase on failure.
*/
protected boolean addURLToDownload(URL url, String prefix) {
// Use empty subdirectory
return addURLToDownload(url, prefix, "");
}
public static String getFileName(URL url, String fileName, String extension) {
String saveAs;
if (fileName != null) {
saveAs = fileName;
} else {
saveAs = url.toExternalForm();
saveAs = saveAs.substring(saveAs.lastIndexOf('/')+1);
}
if (extension == null) {
// Get the extension of the file
String[] lastBitOfURL = url.toExternalForm().split("/");
String[] lastBit = lastBitOfURL[lastBitOfURL.length - 1].split(".");
if (lastBit.length != 0) {
extension = lastBit[lastBit.length - 1];
saveAs = saveAs + "." + extension;
}
}
if (saveAs.indexOf('?') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf('?')); }
if (saveAs.indexOf('#') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf('#')); }
if (saveAs.indexOf('&') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf('&')); }
if (saveAs.indexOf(':') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf(':')); }
if (extension != null) {
saveAs = saveAs + "." + extension;
}
return saveAs;
}
/**
* Waits for downloading threads to complete.
*/
protected void waitForThreads() {
LOGGER.debug("Waiting for threads to finish");
completed = false;
threadPool.waitForThreads();
checkIfComplete();
}
/**
* Notifies observers that source is being retrieved.
* @param url
* URL being retrieved
*/
public void retrievingSource(String url) {
RipStatusMessage msg = new RipStatusMessage(STATUS.LOADING_RESOURCE, url);
if (observer != null) {
observer.update(this, msg);
}
}
/**
* Notifies observers that a file download has completed.
* @param url
* URL that was completed.
* @param saveAs
* Where the downloaded file is stored.
*/
public abstract void downloadCompleted(URL url, File saveAs);
/**
* Notifies observers that a file could not be downloaded (includes a reason).
* @param url
* @param reason
*/
public abstract void downloadErrored(URL url, String reason);
/**
* Notify observers that a download could not be completed,
* but was not technically an "error".
* @param url
* @param file
*/
public abstract void downloadExists(URL url, File file);
/**
* @return Number of files downloaded.
*/
int getCount() {
return 1;
}
/**
* Notifies observers and updates state if all files have been ripped.
*/
void checkIfComplete() {
if (observer == null) {
LOGGER.debug("observer is null");
return;
}
if (!completed) {
completed = true;
LOGGER.info(" Rip completed!");
RipStatusComplete rsc = new RipStatusComplete(workingDir, getCount());
RipStatusMessage msg = new RipStatusMessage(STATUS.RIP_COMPLETE, rsc);
observer.update(this, msg);
Logger rootLogger = Logger.getRootLogger();
FileAppender fa = (FileAppender) rootLogger.getAppender("FILE");
if (fa != null) {
LOGGER.debug("Changing log file back to 'ripme.log'");
fa.setFile("ripme.log");
fa.activateOptions();
}
if (Utils.getConfigBoolean("urls_only.save", false)) {
String urlFile = this.workingDir + File.separator + "urls.txt";
try {
Desktop.getDesktop().open(new File(urlFile));
} catch (IOException e) {
LOGGER.warn("Error while opening " + urlFile, e);
}
}
}
}
/**
* Gets URL
* @return
* Returns URL that wants to be downloaded.
*/
public URL getURL() {
return url;
}
/**
* @return
* Path to the directory in which all files
* ripped via this ripper will be stored.
*/
public File getWorkingDir() {
return workingDir;
}
@Override
public abstract void setWorkingDir(URL url) throws IOException;
/**
*
* @param url
* The URL you want to get the title of.
* @return
* host_URLid
* e.g. (for a reddit post)
* reddit_post_7mg2ur
* @throws MalformedURLException
* If any of those damned URLs gets malformed.
*/
public String getAlbumTitle(URL url) throws MalformedURLException {
return getHost() + "_" + getGID(url);
}
/**
* Finds, instantiates, and returns a compatible ripper for given URL.
* @param url
* URL to rip.
* @return
* Instantiated ripper ready to rip given URL.
* @throws Exception
* If no compatible rippers can be found.
*/
public static AbstractRipper getRipper(URL url) throws Exception {
for (Constructor<?> constructor : getRipperConstructors("com.rarchives.ripme.ripper.rippers")) {
try {
AlbumRipper ripper = (AlbumRipper) constructor.newInstance(url); // by design: can throw ClassCastException
LOGGER.debug("Found album ripper: " + ripper.getClass().getName());
return ripper;
} catch (Exception e) {
// Incompatible rippers *will* throw exceptions during instantiation.
}
}
for (Constructor<?> constructor : getRipperConstructors("com.rarchives.ripme.ripper.rippers.video")) {
try {
VideoRipper ripper = (VideoRipper) constructor.newInstance(url); // by design: can throw ClassCastException
LOGGER.debug("Found video ripper: " + ripper.getClass().getName());
return ripper;
} catch (Exception e) {
// Incompatible rippers *will* throw exceptions during instantiation.
}
}
throw new Exception("No compatible ripper found");
}
/**
* @param pkg
* The package name.
* @return
* List of constructors for all eligible Rippers.
* @throws Exception
*/
public static List<Constructor<?>> getRipperConstructors(String pkg) throws Exception {
List<Constructor<?>> constructors = new ArrayList<>();
for (Class<?> clazz : Utils.getClassesForPackage(pkg)) {
if (AbstractRipper.class.isAssignableFrom(clazz)) {
constructors.add(clazz.getConstructor(URL.class));
}
}
return constructors;
}
/**
* Sends an update message to the relevant observer(s) on this ripper.
* @param status
* @param message
*/
public void sendUpdate(STATUS status, Object message) {
if (observer == null) {
return;
}
observer.update(this, new RipStatusMessage(status, message));
}
/**
* Get the completion percentage.
* @return
* Percentage complete
*/
public abstract int getCompletionPercentage();
/**
* @return
* Text for status
*/
public abstract String getStatusText();
/**
* Rips the album when the thread is invoked.
*/
public void run() {
try {
rip();
} catch (HttpStatusException e) {
LOGGER.error("Got exception while running ripper:", e);
waitForThreads();
sendUpdate(STATUS.RIP_ERRORED, "HTTP status code " + e.getStatusCode() + " for URL " + e.getUrl());
} catch (Exception e) {
LOGGER.error("Got exception while running ripper:", e);
waitForThreads();
sendUpdate(STATUS.RIP_ERRORED, e.getMessage());
} finally {
cleanup();
}
}
/**
* Tries to delete any empty directories
*/
private void cleanup() {
if (this.workingDir.list().length == 0) {
// No files, delete the dir
LOGGER.info("Deleting empty directory " + this.workingDir);
boolean deleteResult = this.workingDir.delete();
if (!deleteResult) {
LOGGER.error("Unable to delete empty directory " + this.workingDir);
}
}
}
/**
* Pauses thread for a set amount of time.
* @param milliseconds
* Amount of time (in milliseconds) that the thread gets paused for
* @return
* True if paused successfully
* False if failed to pause/got interrupted.
*/
protected boolean sleep(int milliseconds) {
try {
LOGGER.debug("Sleeping " + milliseconds + "ms");
Thread.sleep(milliseconds);
return true;
} catch (InterruptedException e) {
LOGGER.error("Interrupted while waiting to load next page", e);
return false;
}
}
public void setBytesTotal(int bytes) {
// Do nothing
}
public void setBytesCompleted(int bytes) {
// Do nothing
}
/** Methods for detecting when we're running a test. */
public void markAsTest() {
LOGGER.debug("THIS IS A TEST RIP");
thisIsATest = true;
}
protected static boolean isThisATest() {
return thisIsATest;
}
// If true ripme uses a byte progress bar
protected boolean useByteProgessBar() { return false;}
// If true ripme will try to resume a broken download for this ripper
protected boolean tryResumeDownload() { return false;}
}
| src/main/java/com/rarchives/ripme/ripper/AbstractRipper.java | package com.rarchives.ripme.ripper;
import java.awt.Desktop;
import java.io.*;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import com.rarchives.ripme.App;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.jsoup.HttpStatusException;
import com.rarchives.ripme.ui.RipStatusComplete;
import com.rarchives.ripme.ui.RipStatusHandler;
import com.rarchives.ripme.ui.RipStatusMessage;
import com.rarchives.ripme.ui.RipStatusMessage.STATUS;
import com.rarchives.ripme.utils.Utils;
import java.io.File;
import java.util.Scanner;
public abstract class AbstractRipper
extends Observable
implements RipperInterface, Runnable {
protected static final Logger LOGGER = Logger.getLogger(AbstractRipper.class);
private final String URLHistoryFile = Utils.getURLHistoryFile();
public static final String USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
protected URL url;
protected File workingDir;
DownloadThreadPool threadPool;
RipStatusHandler observer = null;
private boolean completed = true;
public abstract void rip() throws IOException;
public abstract String getHost();
public abstract String getGID(URL url) throws MalformedURLException;
public boolean hasASAPRipping() { return false; }
// Everytime addUrlToDownload skips a already downloaded url this increases by 1
public int alreadyDownloadedUrls = 0;
private boolean shouldStop = false;
private static boolean thisIsATest = false;
public void stop() {
shouldStop = true;
}
public boolean isStopped() {
return shouldStop;
}
protected void stopCheck() throws IOException {
if (shouldStop) {
throw new IOException("Ripping interrupted");
}
}
/**
* Adds a URL to the url history file
* @param downloadedURL URL to check if downloaded
*/
protected void writeDownloadedURL(String downloadedURL) throws IOException {
// If "save urls only" is checked don't write to the url history file
if (Utils.getConfigBoolean("urls_only.save", false)) {
return;
}
downloadedURL = normalizeUrl(downloadedURL);
BufferedWriter bw = null;
FileWriter fw = null;
try {
File file = new File(URLHistoryFile);
if (!new File(Utils.getConfigDir()).exists()) {
LOGGER.error("Config dir doesn't exist");
LOGGER.info("Making config dir");
boolean couldMakeDir = new File(Utils.getConfigDir()).mkdirs();
if (!couldMakeDir) {
LOGGER.error("Couldn't make config dir");
return;
}
}
// if file doesnt exists, then create it
if (!file.exists()) {
boolean couldMakeDir = file.createNewFile();
if (!couldMakeDir) {
LOGGER.error("Couldn't url history file");
return;
}
}
if (!file.canWrite()) {
LOGGER.error("Can't write to url history file: " + URLHistoryFile);
return;
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(downloadedURL);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* Normalize a URL
* @param url URL to check if downloaded
*/
public String normalizeUrl(String url) {
return url;
}
/**
* Checks to see if Ripme has already downloaded a URL
* @param url URL to check if downloaded
* @return
* Returns true if previously downloaded.
* Returns false if not yet downloaded.
*/
protected boolean hasDownloadedURL(String url) {
File file = new File(URLHistoryFile);
url = normalizeUrl(url);
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.equals(url)) {
return true;
}
}
} catch (FileNotFoundException e) {
return false;
}
return false;
}
/**
* Ensures inheriting ripper can rip this URL, raises exception if not.
* Otherwise initializes working directory and thread pool.
*
* @param url
* URL to rip.
* @throws IOException
* If anything goes wrong.
*/
public AbstractRipper(URL url) throws IOException {
if (!canRip(url)) {
throw new MalformedURLException("Unable to rip url: " + url);
}
this.url = sanitizeURL(url);
}
/**
* Sets ripper's:
* Working directory
* Logger (for debugging)
* FileAppender
* Threadpool
* @throws IOException
* Always be prepared.
*/
public void setup() throws IOException {
setWorkingDir(this.url);
Logger rootLogger = Logger.getRootLogger();
FileAppender fa = (FileAppender) rootLogger.getAppender("FILE");
if (fa != null) {
fa.setFile(this.workingDir + File.separator + "log.txt");
fa.activateOptions();
}
this.threadPool = new DownloadThreadPool();
}
public void setObserver(RipStatusHandler obs) {
this.observer = obs;
}
/**
* Queues image to be downloaded and saved.
* @param url
* URL of the file
* @param saveAs
* Path of the local file to save the content to.
* @return True on success, false on failure.
*/
public abstract boolean addURLToDownload(URL url, File saveAs);
/**
* Queues image to be downloaded and saved.
* @param url
* URL of the file
* @param saveAs
* Path of the local file to save the content to.
* @param referrer
* The HTTP referrer to use while downloading this file.
* @param cookies
* The cookies to send to the server while downloading this file.
* @return
* True if downloaded successfully
* False if failed to download
*/
protected abstract boolean addURLToDownload(URL url, File saveAs, String referrer, Map<String, String> cookies,
Boolean getFileExtFromMIME);
/**
* Queues image to be downloaded and saved.
* @param url
* URL of the file
* @param prefix
* Prefix for the downloaded file
* @param subdirectory
* Path to get to desired directory from working directory
* @param referrer
* The HTTP referrer to use while downloading this file.
* @param cookies
* The cookies to send to the server while downloading this file.
* @param fileName
* The name that file will be written to
* @return
* True if downloaded successfully
* False if failed to download
*/
protected boolean addURLToDownload(URL url, String prefix, String subdirectory, String referrer, Map<String, String> cookies, String fileName, String extension, Boolean getFileExtFromMIME) {
// Don't re-add the url if it was downloaded in a previous rip
if (Utils.getConfigBoolean("remember.url_history", true) && !isThisATest()) {
if (hasDownloadedURL(url.toExternalForm())) {
sendUpdate(STATUS.DOWNLOAD_WARN, "Already downloaded " + url.toExternalForm());
alreadyDownloadedUrls += 1;
return false;
}
}
try {
stopCheck();
} catch (IOException e) {
LOGGER.debug("Ripper has been stopped");
return false;
}
LOGGER.debug("url: " + url + ", prefix: " + prefix + ", subdirectory" + subdirectory + ", referrer: " + referrer + ", cookies: " + cookies + ", fileName: " + fileName);
String saveAs = getFileName(url, fileName, extension);
File saveFileAs;
try {
if (!subdirectory.equals("")) {
subdirectory = Utils.filesystemSafe(subdirectory);
subdirectory = File.separator + subdirectory;
}
prefix = Utils.filesystemSanitized(prefix);
String topFolderName = workingDir.getCanonicalPath();
if (App.stringToAppendToFoldername != null) {
topFolderName = topFolderName + App.stringToAppendToFoldername;
}
saveFileAs = new File(
topFolderName
+ subdirectory
+ File.separator
+ prefix
+ saveAs);
} catch (IOException e) {
LOGGER.error("[!] Error creating save file path for URL '" + url + "':", e);
return false;
}
LOGGER.debug("Downloading " + url + " to " + saveFileAs);
if (!saveFileAs.getParentFile().exists()) {
LOGGER.info("[+] Creating directory: " + Utils.removeCWD(saveFileAs.getParent()));
saveFileAs.getParentFile().mkdirs();
}
if (Utils.getConfigBoolean("remember.url_history", true) && !isThisATest()) {
LOGGER.info("Writing " + url.toExternalForm() + " to file");
try {
writeDownloadedURL(url.toExternalForm() + "\n");
} catch (IOException e) {
LOGGER.debug("Unable to write URL history file");
}
}
return addURLToDownload(url, saveFileAs, referrer, cookies, getFileExtFromMIME);
}
protected boolean addURLToDownload(URL url, String prefix, String subdirectory, String referrer, Map<String,String> cookies, String fileName, String extension) {
return addURLToDownload(url, prefix, subdirectory, referrer, cookies, fileName, extension, false);
}
protected boolean addURLToDownload(URL url, String prefix, String subdirectory, String referrer, Map<String, String> cookies, String fileName) {
return addURLToDownload(url, prefix, subdirectory, referrer, cookies, fileName, null);
}
/**
* Queues file to be downloaded and saved. With options.
* @param url
* URL to download.
* @param prefix
* Prefix to prepend to the saved filename.
* @param subdirectory
* Sub-directory of the working directory to save the images to.
* @return True on success, flase on failure.
*/
protected boolean addURLToDownload(URL url, String prefix, String subdirectory) {
return addURLToDownload(url, prefix, subdirectory, null, null, null);
}
protected boolean addURLToDownload(URL url, String prefix, String subdirectory, String referrer, Map<String, String> cookies) {
return addURLToDownload(url, prefix, subdirectory, referrer, cookies, null);
}
/**
* Queues image to be downloaded and saved.
* Uses filename from URL (and 'prefix') to decide filename.
* @param url
* URL to download
* @param prefix
* Text to append to saved filename.
* @return True on success, flase on failure.
*/
protected boolean addURLToDownload(URL url, String prefix) {
// Use empty subdirectory
return addURLToDownload(url, prefix, "");
}
public static String getFileName(URL url, String fileName, String extension) {
String saveAs;
if (fileName != null) {
saveAs = fileName;
} else {
saveAs = url.toExternalForm();
saveAs = saveAs.substring(saveAs.lastIndexOf('/')+1);
}
if (extension == null) {
// Get the extension of the file
String[] lastBitOfURL = url.toExternalForm().split("/");
String[] lastBit = lastBitOfURL[lastBitOfURL.length - 1].split(".");
if (lastBit.length != 0) {
extension = lastBit[lastBit.length - 1];
saveAs = saveAs + "." + extension;
}
}
if (saveAs.indexOf('?') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf('?')); }
if (saveAs.indexOf('#') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf('#')); }
if (saveAs.indexOf('&') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf('&')); }
if (saveAs.indexOf(':') >= 0) { saveAs = saveAs.substring(0, saveAs.indexOf(':')); }
if (extension != null) {
saveAs = saveAs + "." + extension;
}
return saveAs;
}
/**
* Waits for downloading threads to complete.
*/
protected void waitForThreads() {
LOGGER.debug("Waiting for threads to finish");
completed = false;
threadPool.waitForThreads();
checkIfComplete();
}
/**
* Notifies observers that source is being retrieved.
* @param url
* URL being retrieved
*/
public void retrievingSource(String url) {
RipStatusMessage msg = new RipStatusMessage(STATUS.LOADING_RESOURCE, url);
if (observer != null) {
observer.update(this, msg);
}
}
/**
* Notifies observers that a file download has completed.
* @param url
* URL that was completed.
* @param saveAs
* Where the downloaded file is stored.
*/
public abstract void downloadCompleted(URL url, File saveAs);
/**
* Notifies observers that a file could not be downloaded (includes a reason).
* @param url
* @param reason
*/
public abstract void downloadErrored(URL url, String reason);
/**
* Notify observers that a download could not be completed,
* but was not technically an "error".
* @param url
* @param file
*/
public abstract void downloadExists(URL url, File file);
/**
* @return Number of files downloaded.
*/
int getCount() {
return 1;
}
/**
* Notifies observers and updates state if all files have been ripped.
*/
void checkIfComplete() {
if (observer == null) {
LOGGER.debug("observer is null");
return;
}
if (!completed) {
completed = true;
LOGGER.info(" Rip completed!");
RipStatusComplete rsc = new RipStatusComplete(workingDir, getCount());
RipStatusMessage msg = new RipStatusMessage(STATUS.RIP_COMPLETE, rsc);
observer.update(this, msg);
Logger rootLogger = Logger.getRootLogger();
FileAppender fa = (FileAppender) rootLogger.getAppender("FILE");
if (fa != null) {
LOGGER.debug("Changing log file back to 'ripme.log'");
fa.setFile("ripme.log");
fa.activateOptions();
}
if (Utils.getConfigBoolean("urls_only.save", false)) {
String urlFile = this.workingDir + File.separator + "urls.txt";
try {
Desktop.getDesktop().open(new File(urlFile));
} catch (IOException e) {
LOGGER.warn("Error while opening " + urlFile, e);
}
}
}
}
/**
* Gets URL
* @return
* Returns URL that wants to be downloaded.
*/
public URL getURL() {
return url;
}
/**
* @return
* Path to the directory in which all files
* ripped via this ripper will be stored.
*/
public File getWorkingDir() {
return workingDir;
}
@Override
public abstract void setWorkingDir(URL url) throws IOException;
/**
*
* @param url
* The URL you want to get the title of.
* @return
* host_URLid
* e.g. (for a reddit post)
* reddit_post_7mg2ur
* @throws MalformedURLException
* If any of those damned URLs gets malformed.
*/
public String getAlbumTitle(URL url) throws MalformedURLException {
return getHost() + "_" + getGID(url);
}
/**
* Finds, instantiates, and returns a compatible ripper for given URL.
* @param url
* URL to rip.
* @return
* Instantiated ripper ready to rip given URL.
* @throws Exception
* If no compatible rippers can be found.
*/
public static AbstractRipper getRipper(URL url) throws Exception {
for (Constructor<?> constructor : getRipperConstructors("com.rarchives.ripme.ripper.rippers")) {
try {
AlbumRipper ripper = (AlbumRipper) constructor.newInstance(url); // by design: can throw ClassCastException
LOGGER.debug("Found album ripper: " + ripper.getClass().getName());
return ripper;
} catch (Exception e) {
// Incompatible rippers *will* throw exceptions during instantiation.
}
}
for (Constructor<?> constructor : getRipperConstructors("com.rarchives.ripme.ripper.rippers.video")) {
try {
VideoRipper ripper = (VideoRipper) constructor.newInstance(url); // by design: can throw ClassCastException
LOGGER.debug("Found video ripper: " + ripper.getClass().getName());
return ripper;
} catch (Exception e) {
// Incompatible rippers *will* throw exceptions during instantiation.
}
}
throw new Exception("No compatible ripper found");
}
/**
* @param pkg
* The package name.
* @return
* List of constructors for all eligible Rippers.
* @throws Exception
*/
public static List<Constructor<?>> getRipperConstructors(String pkg) throws Exception {
List<Constructor<?>> constructors = new ArrayList<>();
for (Class<?> clazz : Utils.getClassesForPackage(pkg)) {
if (AbstractRipper.class.isAssignableFrom(clazz)) {
constructors.add(clazz.getConstructor(URL.class));
}
}
return constructors;
}
/**
* Sends an update message to the relevant observer(s) on this ripper.
* @param status
* @param message
*/
public void sendUpdate(STATUS status, Object message) {
if (observer == null) {
return;
}
observer.update(this, new RipStatusMessage(status, message));
}
/**
* Get the completion percentage.
* @return
* Percentage complete
*/
public abstract int getCompletionPercentage();
/**
* @return
* Text for status
*/
public abstract String getStatusText();
/**
* Rips the album when the thread is invoked.
*/
public void run() {
try {
rip();
} catch (HttpStatusException e) {
LOGGER.error("Got exception while running ripper:", e);
waitForThreads();
sendUpdate(STATUS.RIP_ERRORED, "HTTP status code " + e.getStatusCode() + " for URL " + e.getUrl());
} catch (Exception e) {
LOGGER.error("Got exception while running ripper:", e);
waitForThreads();
sendUpdate(STATUS.RIP_ERRORED, e.getMessage());
} finally {
cleanup();
}
}
/**
* Tries to delete any empty directories
*/
private void cleanup() {
if (this.workingDir.list().length == 0) {
// No files, delete the dir
LOGGER.info("Deleting empty directory " + this.workingDir);
boolean deleteResult = this.workingDir.delete();
if (!deleteResult) {
LOGGER.error("Unable to delete empty directory " + this.workingDir);
}
}
}
/**
* Pauses thread for a set amount of time.
* @param milliseconds
* Amount of time (in milliseconds) that the thread gets paused for
* @return
* True if paused successfully
* False if failed to pause/got interrupted.
*/
protected boolean sleep(int milliseconds) {
try {
LOGGER.debug("Sleeping " + milliseconds + "ms");
Thread.sleep(milliseconds);
return true;
} catch (InterruptedException e) {
LOGGER.error("Interrupted while waiting to load next page", e);
return false;
}
}
public void setBytesTotal(int bytes) {
// Do nothing
}
public void setBytesCompleted(int bytes) {
// Do nothing
}
/** Methods for detecting when we're running a test. */
public void markAsTest() {
LOGGER.debug("THIS IS A TEST RIP");
thisIsATest = true;
}
protected static boolean isThisATest() {
return thisIsATest;
}
// If true ripme uses a byte progress bar
protected boolean useByteProgessBar() { return false;}
// If true ripme will try to resume a broken download for this ripper
protected boolean tryResumeDownload() { return false;}
}
| Now handles urls with spaces in them
| src/main/java/com/rarchives/ripme/ripper/AbstractRipper.java | Now handles urls with spaces in them | <ide><path>rc/main/java/com/rarchives/ripme/ripper/AbstractRipper.java
<ide> * False if failed to download
<ide> */
<ide> protected boolean addURLToDownload(URL url, String prefix, String subdirectory, String referrer, Map<String, String> cookies, String fileName, String extension, Boolean getFileExtFromMIME) {
<add> // Make sure the url doesn't contain any spaces as that can cause a 400 error when requesting the file
<add> if (url.toExternalForm().contains(" ")) {
<add> // If for some reason the url with all spaces encoded as %20 is malformed print an error
<add> try {
<add> url = new URL(url.toExternalForm().replaceAll(" ", "%20"));
<add> } catch (MalformedURLException e) {
<add> LOGGER.error("Unable to remove spaces from url\nURL: " + url.toExternalForm());
<add> e.printStackTrace();
<add> }
<add> }
<ide> // Don't re-add the url if it was downloaded in a previous rip
<ide> if (Utils.getConfigBoolean("remember.url_history", true) && !isThisATest()) {
<ide> if (hasDownloadedURL(url.toExternalForm())) { |
|
Java | apache-2.0 | b3b2d6d5e6c00de4a947fd4a9a9c539f33852acd | 0 | opetrovski/development,opetrovski/development,opetrovski/development,opetrovski/development,opetrovski/development | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2015
*
* Creation Date: 2009-02-05
*
*******************************************************************************/
package org.oscm.subscriptionservice.bean;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.interceptor.Interceptors;
import org.oscm.accountservice.assembler.OrganizationAssembler;
import org.oscm.accountservice.assembler.UdaAssembler;
import org.oscm.accountservice.dataaccess.UdaAccess;
import org.oscm.accountservice.local.AccountServiceLocal;
import org.oscm.applicationservice.local.ApplicationServiceLocal;
import org.oscm.communicationservice.local.CommunicationServiceLocal;
import org.oscm.configurationservice.local.ConfigurationServiceLocal;
import org.oscm.converter.ParameterizedTypes;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.BillingContact;
import org.oscm.domobjects.CatalogEntry;
import org.oscm.domobjects.Marketplace;
import org.oscm.domobjects.OnBehalfUserReference;
import org.oscm.domobjects.OperationParameter;
import org.oscm.domobjects.OperationRecord;
import org.oscm.domobjects.Organization;
import org.oscm.domobjects.OrganizationRefToPaymentType;
import org.oscm.domobjects.OrganizationReference;
import org.oscm.domobjects.OrganizationRole;
import org.oscm.domobjects.OrganizationToRole;
import org.oscm.domobjects.Parameter;
import org.oscm.domobjects.ParameterDefinition;
import org.oscm.domobjects.ParameterSet;
import org.oscm.domobjects.PaymentInfo;
import org.oscm.domobjects.PaymentType;
import org.oscm.domobjects.PlatformUser;
import org.oscm.domobjects.PriceModel;
import org.oscm.domobjects.Product;
import org.oscm.domobjects.RoleDefinition;
import org.oscm.domobjects.Session;
import org.oscm.domobjects.Subscription;
import org.oscm.domobjects.TechnicalProduct;
import org.oscm.domobjects.TechnicalProductOperation;
import org.oscm.domobjects.TriggerDefinition;
import org.oscm.domobjects.TriggerProcess;
import org.oscm.domobjects.TriggerProcessIdentifier;
import org.oscm.domobjects.TriggerProcessParameter;
import org.oscm.domobjects.Uda;
import org.oscm.domobjects.UsageLicense;
import org.oscm.domobjects.UserGroup;
import org.oscm.domobjects.enums.LocalizedObjectTypes;
import org.oscm.domobjects.enums.ModifiedEntityType;
import org.oscm.domobjects.enums.OrganizationReferenceType;
import org.oscm.i18nservice.bean.LocalizerFacade;
import org.oscm.i18nservice.local.LocalizerServiceLocal;
import org.oscm.id.IdGenerator;
import org.oscm.identityservice.assembler.UserDataAssembler;
import org.oscm.identityservice.local.IdentityServiceLocal;
import org.oscm.interceptor.AuditLogDataInterceptor;
import org.oscm.interceptor.DateFactory;
import org.oscm.interceptor.ExceptionMapper;
import org.oscm.interceptor.InvocationDateContainer;
import org.oscm.internal.intf.SubscriptionService;
import org.oscm.internal.tables.Pagination;
import org.oscm.internal.types.enumtypes.ConfigurationKey;
import org.oscm.internal.types.enumtypes.OperationStatus;
import org.oscm.internal.types.enumtypes.OrganizationRoleType;
import org.oscm.internal.types.enumtypes.ParameterModificationType;
import org.oscm.internal.types.enumtypes.ParameterType;
import org.oscm.internal.types.enumtypes.PerformanceHint;
import org.oscm.internal.types.enumtypes.ServiceAccessType;
import org.oscm.internal.types.enumtypes.ServiceStatus;
import org.oscm.internal.types.enumtypes.ServiceType;
import org.oscm.internal.types.enumtypes.SubscriptionStatus;
import org.oscm.internal.types.enumtypes.TriggerType;
import org.oscm.internal.types.enumtypes.UserRoleType;
import org.oscm.internal.types.exception.ConcurrentModificationException;
import org.oscm.internal.types.exception.DomainObjectException;
import org.oscm.internal.types.exception.IllegalArgumentException;
import org.oscm.internal.types.exception.MailOperationException;
import org.oscm.internal.types.exception.MandatoryUdaMissingException;
import org.oscm.internal.types.exception.NonUniqueBusinessKeyException;
import org.oscm.internal.types.exception.ObjectNotFoundException;
import org.oscm.internal.types.exception.OperationNotPermittedException;
import org.oscm.internal.types.exception.OperationPendingException;
import org.oscm.internal.types.exception.OperationPendingException.ReasonEnum;
import org.oscm.internal.types.exception.OperationStateException;
import org.oscm.internal.types.exception.OrganizationAuthoritiesException;
import org.oscm.internal.types.exception.PaymentDataException;
import org.oscm.internal.types.exception.PaymentInformationException;
import org.oscm.internal.types.exception.PriceModelException;
import org.oscm.internal.types.exception.SaaSApplicationException;
import org.oscm.internal.types.exception.SaaSSystemException;
import org.oscm.internal.types.exception.ServiceChangedException;
import org.oscm.internal.types.exception.ServiceParameterException;
import org.oscm.internal.types.exception.SubscriptionAlreadyExistsException;
import org.oscm.internal.types.exception.SubscriptionMigrationException;
import org.oscm.internal.types.exception.SubscriptionMigrationException.Reason;
import org.oscm.internal.types.exception.SubscriptionStateException;
import org.oscm.internal.types.exception.SubscriptionStillActiveException;
import org.oscm.internal.types.exception.TechnicalServiceNotAliveException;
import org.oscm.internal.types.exception.TechnicalServiceOperationException;
import org.oscm.internal.types.exception.ValidationException;
import org.oscm.internal.vo.VOBillingContact;
import org.oscm.internal.vo.VOInstanceInfo;
import org.oscm.internal.vo.VOLocalizedText;
import org.oscm.internal.vo.VOOrganization;
import org.oscm.internal.vo.VOParameter;
import org.oscm.internal.vo.VOPaymentInfo;
import org.oscm.internal.vo.VORoleDefinition;
import org.oscm.internal.vo.VOService;
import org.oscm.internal.vo.VOServiceOperationParameter;
import org.oscm.internal.vo.VOServiceOperationParameterValues;
import org.oscm.internal.vo.VOSubscription;
import org.oscm.internal.vo.VOSubscriptionDetails;
import org.oscm.internal.vo.VOSubscriptionIdAndOrganizations;
import org.oscm.internal.vo.VOTechnicalServiceOperation;
import org.oscm.internal.vo.VOUda;
import org.oscm.internal.vo.VOUsageLicense;
import org.oscm.internal.vo.VOUser;
import org.oscm.internal.vo.VOUserSubscription;
import org.oscm.logging.Log4jLogger;
import org.oscm.logging.LoggerFactory;
import org.oscm.notification.vo.VONotification;
import org.oscm.notification.vo.VOProperty;
import org.oscm.operation.data.OperationResult;
import org.oscm.permission.PermissionCheck;
import org.oscm.provisioning.data.User;
import org.oscm.serviceprovisioningservice.assembler.ProductAssembler;
import org.oscm.serviceprovisioningservice.assembler.RoleAssembler;
import org.oscm.serviceprovisioningservice.assembler.TechServiceOperationParameterAssembler;
import org.oscm.sessionservice.local.SessionServiceLocal;
import org.oscm.string.Strings;
import org.oscm.subscriptionservice.assembler.SubscriptionAssembler;
import org.oscm.subscriptionservice.auditlog.SubscriptionAuditLogCollector;
import org.oscm.subscriptionservice.dao.MarketplaceDao;
import org.oscm.subscriptionservice.dao.ModifiedEntityDao;
import org.oscm.subscriptionservice.dao.OrganizationDao;
import org.oscm.subscriptionservice.dao.ProductDao;
import org.oscm.subscriptionservice.dao.SessionDao;
import org.oscm.subscriptionservice.dao.SubscriptionDao;
import org.oscm.subscriptionservice.dao.SubscriptionHistoryDao;
import org.oscm.subscriptionservice.dao.UsageLicenseDao;
import org.oscm.subscriptionservice.local.SubscriptionListServiceLocal;
import org.oscm.subscriptionservice.local.SubscriptionServiceLocal;
import org.oscm.taskhandling.local.TaskMessage;
import org.oscm.taskhandling.local.TaskQueueServiceLocal;
import org.oscm.taskhandling.operations.NotifyProvisioningServiceHandler;
import org.oscm.taskhandling.operations.SendMailHandler;
import org.oscm.taskhandling.payloads.NotifyProvisioningServicePayload;
import org.oscm.taskhandling.payloads.SendMailPayload;
import org.oscm.techproductoperation.bean.OperationRecordServiceLocalBean;
import org.oscm.tenantprovisioningservice.bean.TenantProvisioningServiceBean;
import org.oscm.tenantprovisioningservice.vo.TenantProvisioningResult;
import org.oscm.triggerservice.bean.TriggerProcessIdentifiers;
import org.oscm.triggerservice.local.TriggerMessage;
import org.oscm.triggerservice.local.TriggerProcessMessageData;
import org.oscm.triggerservice.local.TriggerQueueServiceLocal;
import org.oscm.triggerservice.notification.VONotificationBuilder;
import org.oscm.triggerservice.validator.TriggerProcessValidator;
import org.oscm.types.constants.Configuration;
import org.oscm.types.enumtypes.EmailType;
import org.oscm.types.enumtypes.LogMessageIdentifier;
import org.oscm.types.enumtypes.PlatformParameterIdentifiers;
import org.oscm.types.enumtypes.ProvisioningType;
import org.oscm.types.enumtypes.TriggerProcessIdentifierName;
import org.oscm.types.enumtypes.TriggerProcessParameterName;
import org.oscm.types.enumtypes.UdaTargetType;
import org.oscm.types.exceptions.UserAlreadyAssignedException;
import org.oscm.types.exceptions.UserNotAssignedException;
import org.oscm.usergroupservice.bean.UserGroupServiceLocalBean;
import org.oscm.validation.ArgumentValidator;
import org.oscm.validation.PaymentDataValidator;
import org.oscm.validator.ADMValidator;
import org.oscm.validator.BLValidator;
import org.oscm.vo.BaseAssembler;
/**
* Session Bean implementation class of SubscriptionService (Remote IF) and
* SubscriptionServiceLocal (Local IF)
*/
@Stateless
@Remote(SubscriptionService.class)
@Local(SubscriptionServiceLocal.class)
@Interceptors({ InvocationDateContainer.class, ExceptionMapper.class,
AuditLogDataInterceptor.class })
public class SubscriptionServiceBean implements SubscriptionService,
SubscriptionServiceLocal {
public static final String KEY_PAIR_NAME = "Key pair name";
public static final String AMAZONAWS_COM = "amazonaws.com";
private static final Log4jLogger LOG = LoggerFactory
.getLogger(SubscriptionServiceBean.class);
@EJB(beanInterface = ApplicationServiceLocal.class)
protected ApplicationServiceLocal appManager;
@EJB(beanInterface = SessionServiceLocal.class)
protected SessionServiceLocal prodSessionMgmt;
@EJB
protected DataService dataManager;
@EJB
protected IdentityServiceLocal idManager;
@EJB
protected TenantProvisioningServiceBean tenantProvisioning;
@EJB
protected CommunicationServiceLocal commService;
@EJB(beanInterface = LocalizerServiceLocal.class)
protected LocalizerServiceLocal localizer;
@EJB(beanInterface = ConfigurationServiceLocal.class)
ConfigurationServiceLocal cfgService;
@EJB(beanInterface = SubscriptionListServiceLocal.class)
SubscriptionListServiceLocal subscriptionListService;
@EJB(beanInterface = TriggerQueueServiceLocal.class)
protected TriggerQueueServiceLocal triggerQS;
@EJB(beanInterface = TaskQueueServiceLocal.class)
public TaskQueueServiceLocal tqs;
@EJB(beanInterface = AccountServiceLocal.class)
public AccountServiceLocal accountService;
@EJB
SubscriptionAuditLogCollector audit;
@Resource
protected SessionContext sessionCtx;
@Inject
public TerminateSubscriptionBean terminateBean;
@Inject
public ManageSubscriptionBean manageBean;
@Inject
public ValidateSubscriptionStateBean stateValidator;
@Inject
public ModifyAndUpgradeSubscriptionBean modUpgBean;
@Inject
public OperationRecordServiceLocalBean operationRecordBean;
@Inject
UserGroupServiceLocalBean userGroupService;
private static final List<SubscriptionStatus> VISIBLE_SUBSCRIPTION_STATUS = Arrays
.asList(SubscriptionStatus.ACTIVE, SubscriptionStatus.EXPIRED,
SubscriptionStatus.PENDING, SubscriptionStatus.PENDING_UPD,
SubscriptionStatus.SUSPENDED,
SubscriptionStatus.SUSPENDED_UPD);
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public VOSubscription subscribeToService(VOSubscription subscription,
VOService service, List<VOUsageLicense> users,
VOPaymentInfo paymentInfo, VOBillingContact billingContact,
List<VOUda> udas) throws ObjectNotFoundException,
NonUniqueBusinessKeyException, ValidationException,
PaymentInformationException, ServiceParameterException,
ServiceChangedException, PriceModelException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationNotPermittedException,
SubscriptionAlreadyExistsException, OperationPendingException,
MandatoryUdaMissingException, ConcurrentModificationException,
SubscriptionStateException {
ArgumentValidator.notNull("subscription", subscription);
ArgumentValidator.notNull("service", service);
Subscription sub;
PlatformUser currentUser = dataManager.getCurrentUser();
checkIfServiceAvailable(service.getKey(), service.getServiceId(),
currentUser);
checkIfSubscriptionAlreadyExists(service);
verifyIdAndKeyUniqueness(currentUser, subscription);
validateSettingsForSubscribing(subscription, service, paymentInfo,
billingContact);
validateUserAssignmentForSubscribing(service, users);
validateTriggerProcessForCreateSubscription(subscription);
TriggerProcess triggerProcess = createTriggerProcessForCreateSubscription(
subscription, service, users, paymentInfo, billingContact, udas);
VOSubscription voSub = null;
TriggerDefinition triggerDefinition = triggerProcess
.getTriggerDefinition();
if (triggerDefinition == null) {
try {
sub = subscribeToServiceInt(triggerProcess);
voSub = SubscriptionAssembler.toVOSubscription(sub,
new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale()));
autoAssignUser(service, sub);
} catch (ObjectNotFoundException | ValidationException
| ServiceChangedException | PriceModelException
| PaymentInformationException
| NonUniqueBusinessKeyException
| TechnicalServiceNotAliveException
| TechnicalServiceOperationException
| ServiceParameterException
| ConcurrentModificationException
| MandatoryUdaMissingException | SubscriptionStateException e) {
sessionCtx.setRollbackOnly();
throw e;
}
} else if (triggerDefinition.isSuspendProcess()) {
triggerProcess
.setTriggerProcessIdentifiers(TriggerProcessIdentifiers
.createUnsubscribeFromService(dataManager,
TriggerType.SUBSCRIBE_TO_SERVICE,
subscription.getSubscriptionId()));
dataManager.merge(triggerProcess);
}
return voSub;
}
private void autoAssignUser(VOService service, Subscription sub)
throws ObjectNotFoundException, ServiceParameterException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationNotPermittedException,
ConcurrentModificationException {
Product prod = dataManager
.getReference(Product.class, service.getKey());
TechnicalProduct techProd = prod.getTechnicalProduct();
if (ProvisioningType.SYNCHRONOUS.equals(techProd.getProvisioningType())
&& service.isAutoAssignUserEnabled().booleanValue()) {
assignUsersForSubscription(sub.getSubscriptionId(), service);
}
}
void assignUsersForSubscription(String subscriptionId, VOService service)
throws ObjectNotFoundException, ServiceParameterException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationNotPermittedException,
ConcurrentModificationException {
PlatformUser currentUser = dataManager.getCurrentUser();
assignUsersForSubscription(subscriptionId, service, currentUser);
}
void assignUsersForSubscription(String subscriptionId, VOService service,
PlatformUser userToAssign) throws ObjectNotFoundException,
OperationNotPermittedException, ServiceParameterException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, ConcurrentModificationException {
List<VORoleDefinition> serviceRoles = getServiceRolesForService(service);
// If the service roles are defined for technical service,
// assign the first role to user to avoid assignment failure.
// If service roles are not defined, set default role to null.
List<VOUsageLicense> usersToBeAdded = new ArrayList<>();
VOUsageLicense lic = new VOUsageLicense();
lic.setUser(UserDataAssembler.toVOUserDetails(userToAssign));
lic.setRoleDefinition((serviceRoles == null || serviceRoles.isEmpty()) ? null
: serviceRoles.get(0));
usersToBeAdded.add(lic);
TriggerProcess proc = new TriggerProcess();
proc.addTriggerProcessParameter(TriggerProcessParameterName.OBJECT_ID,
subscriptionId);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscriptionId);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.USERS_TO_ADD, usersToBeAdded);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.USERS_TO_REVOKE, null);
addRevokeUserInt(proc);
}
/**
* @param subscription
* @return
* @throws OperationPendingException
*/
private void validateTriggerProcessForCreateSubscription(
VOSubscription subscription) throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
String subscriptionId = subscription.getSubscriptionId();
if (validator.isSubscribeOrUnsubscribeServicePending(subscriptionId)) {
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to create a subscription or unsubscribe from the subscription with identifier '%s'",
subscriptionId), ReasonEnum.SUBSCRIBE_TO_SERVICE,
new Object[] { subscriptionId });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_SUBSCRIBE_TO_SERVICE_FAILED_DUE_TO_TRIGGER_CONFLICT,
subscriptionId);
throw ope;
}
}
private TriggerProcess createTriggerProcessForCreateSubscription(
VOSubscription subscription, VOService service,
List<VOUsageLicense> users, VOPaymentInfo paymentInfo,
VOBillingContact billingContact, List<VOUda> udas) {
TriggerMessage message = new TriggerMessage(
TriggerType.SUBSCRIBE_TO_SERVICE);
List<TriggerProcessMessageData> list = triggerQS
.sendSuspendingMessages(Collections.singletonList(message));
TriggerProcess triggerProcess = list.get(0).getTrigger();
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.OBJECT_ID,
subscription.getSubscriptionId());
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscription);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.PRODUCT, service);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.USERS, users);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.PAYMENTINFO, paymentInfo);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.BILLING_CONTACT, billingContact);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.UDAS, udas);
return triggerProcess;
}
void saveUdasForSubscription(List<VOUda> udas, Subscription subscription)
throws ObjectNotFoundException, NonUniqueBusinessKeyException,
ValidationException, OperationNotPermittedException,
ConcurrentModificationException, MandatoryUdaMissingException {
Organization supplier = subscription.getProduct()
.getSupplierOrResellerTemplate().getVendor();
UdaAccess udaAccess = new UdaAccess(dataManager, sessionCtx);
udaAccess.saveUdasForSubscription(udas, supplier, subscription);
}
/**
* Checks if the technical product the marketing service belongs to has
* service roles defined and if the roles defined for the user assignments
* are part of this set and defined.
*
* @param product
* the product to subscribe to
* @param users
* the users to assign
* @throws ObjectNotFoundException
* if the product or a role wasn't found
* @throws OperationNotPermittedException
* if the role to assign doesn't belong to the products
* technical product or if no role is set when using service
* roles.
*/
private void validateUserAssignmentForSubscribing(VOService product,
List<VOUsageLicense> users) throws ObjectNotFoundException,
OperationNotPermittedException {
Product prod = dataManager
.getReference(Product.class, product.getKey());
if (users == null) {
return;
}
for (VOUsageLicense lic : users) {
getAndCheckServiceRole(lic, prod);
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public Subscription subscribeToServiceInt(TriggerProcess tp)
throws ObjectNotFoundException, ValidationException,
OperationNotPermittedException, ServiceChangedException,
PriceModelException, PaymentInformationException,
NonUniqueBusinessKeyException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, ServiceParameterException,
SubscriptionAlreadyExistsException,
ConcurrentModificationException, MandatoryUdaMissingException,
SubscriptionStateException {
PlatformUser currentUser = dataManager.getCurrentUser();
Organization organization = currentUser.getOrganization();
// read parameters from trigger process
VOSubscription subscription = tp.getParamValueForName(
TriggerProcessParameterName.SUBSCRIPTION).getValue(
VOSubscription.class);
VOService product = tp.getParamValueForName(
TriggerProcessParameterName.PRODUCT).getValue(VOService.class);
VOPaymentInfo voPaymentInfo = tp.getParamValueForName(
TriggerProcessParameterName.PAYMENTINFO).getValue(
VOPaymentInfo.class);
VOBillingContact voBillingContact = tp.getParamValueForName(
TriggerProcessParameterName.BILLING_CONTACT).getValue(
VOBillingContact.class);
List<?> udas = tp
.getParamValueForName(TriggerProcessParameterName.UDAS)
.getValue(List.class);
PlatformUser owner = dataManager.getReference(PlatformUser.class, tp
.getUser().getKey());
checkIfSubscriptionAlreadyExists(product);
UserGroup unit = getUnit(subscription.getUnitKey(),
subscription.getUnitName(), organization.getKey());
validateSettingsForSubscribing(subscription, product, voPaymentInfo,
voBillingContact);
Product productTemplate = dataManager.getReference(Product.class,
product.getKey());
Organization vendor = productTemplate.getVendor();
Organization supplier = dataManager
.getReference(Product.class, product.getKey())
.getSupplierOrResellerTemplate().getVendor();
List<VOUda> originalCustomerUdas = getUdasForCustomer("CUSTOMER",
dataManager.getCurrentUser().getOrganization().getKey(),
supplier);
OrganizationReference refVendorCust = null;
if (!organization.getVendorsOfCustomer().contains(vendor)) {
refVendorCust = new OrganizationReference(vendor, organization,
OrganizationReferenceType
.getOrgRefTypeForSourceRoles(vendor
.getGrantedRoleTypes()));
dataManager.persist(refVendorCust);
}
if (vendor.getGrantedRoleTypes().contains(OrganizationRoleType.BROKER)
&& !organization.getVendorsOfCustomer().contains(
productTemplate.getTemplate().getVendor())) {
refVendorCust = new OrganizationReference(productTemplate
.getTemplate().getVendor(), organization,
OrganizationReferenceType.SUPPLIER_TO_CUSTOMER);
dataManager.persist(refVendorCust);
}
if (refVendorCust != null) {
enableDefaultPaymentsForCustomer(refVendorCust);
}
// Look for the marketplace where the service is published
Marketplace mp = null;
Product publishedService = productTemplate.getType() == ServiceType.CUSTOMER_TEMPLATE ? productTemplate
.getTemplate() : productTemplate;
List<Marketplace> mps = getMarketplaceDao().getMarketplaceByService(
publishedService);
for (Marketplace m : mps) {
mp = m; // current assumption is that there's only one marketplace
break;
}
// Create a new subscription object
Subscription newSub = new Subscription();
Long creationTime = Long.valueOf(DateFactory.getInstance()
.getTransactionTime());
newSub.setCreationDate(creationTime);
newSub.setStatus(SubscriptionStatus.PENDING);
// set default cut-off day (db unique constrain)
newSub.setCutOffDay(1);
newSub.setSubscriptionId(subscription.getSubscriptionId().trim());
newSub.setPurchaseOrderNumber(subscription.getPurchaseOrderNumber());
newSub.setOrganization(organization);
// for subscribing service, set the current user as subscription owner
newSub.setOwner(owner);
verifyUnitAndRoles(currentUser, unit, newSub);
Product theProduct = productTemplate.copyForSubscription(
productTemplate.getTargetCustomer(), newSub);
if (theProduct.getPriceModel() != null) {
// FIXME LG clean
// The first target pricemodel version is created when subscription
// is still in PENDING, but must be fitered for billing. Set the
// indicating flag before persisting.
theProduct.getPriceModel().setProvisioningCompleted(false);
}
// to avoid id conflicts in high load scenarios add customer
// organization hash
theProduct.setProductId(theProduct.getProductId()
+ organization.hashCode());
theProduct.setOwningSubscription(null);
// subscription copies do not have/need a CatalogEntry
theProduct.setCatalogEntries(new ArrayList<CatalogEntry>());
try {
dataManager.persist(theProduct);
} catch (NonUniqueBusinessKeyException e) {
SaaSSystemException sse = new SaaSSystemException(
"The product copy for product '"
+ product.getKey()
+ "' cannot be stored, as the business key already exists.",
e);
LOG.logError(
Log4jLogger.SYSTEM_LOG,
sse,
LogMessageIdentifier.ERROR_CREATE_CUSTOMER_FOR_SPECIFIC_PRICEMODEL_FAILED,
Long.toString(dataManager.getCurrentUser().getKey()));
throw sse;
}
copyLocalizedPricemodelValues(theProduct, productTemplate);
// update the subscription's configurable parameter
List<Parameter> modifiedParametersForLog = updateConfiguredParameterValues(
theProduct, product.getParameters(), null);
// now bind the product and the price model to the subscription:
newSub.bindToProduct(theProduct);
// register the marketplace the subscription was coming from
newSub.setMarketplace(mp);
// Link the passed payment information to this subscription
if (voPaymentInfo != null) {
PaymentInfo paymentInfo = dataManager.getReference(
PaymentInfo.class, voPaymentInfo.getKey());
newSub.setPaymentInfo(paymentInfo);
}
if (voBillingContact != null) {
BillingContact bc = dataManager.getReference(BillingContact.class,
voBillingContact.getKey());
newSub.setBillingContact(bc);
}
// persist the subscription. This is essential to ensure the
// subscription exists and also eliminates all potential problems
// with a subsequent call to the application.
dataManager.persist(newSub);
theProduct.setOwningSubscription(newSub);
createAllowOnBehalfActingReference(newSub);
TenantProvisioningResult provisioningResult = createInstanceAndAddUsersToSubscription(
tp, newSub);
newSub.setSuccessMessage(provisioningResult.getResultMesage());
dataManager.flush();
saveUdasForSubscription(ParameterizedTypes.list(udas, VOUda.class),
newSub);
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.SUBSCRIPTION_CREATION,
tp.getTriggerProcessParameters(), vendor));
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.SUBSCRIBE_TO_SERVICE, tp
.getTriggerProcessParameters(), dataManager
.getCurrentUser().getOrganization()));
sendSubscriptionCreatedMailToAdministrators(newSub, newSub.getProduct()
.getTechnicalProduct().isAllowingOnBehalfActing());
// Used for Autoassign a service which was supended via trigger
// (subscribeToService)
autoAssignUserForTriggerProcess(tp, product, owner, newSub);
audit.editSubscriptionParameterConfiguration(dataManager, theProduct,
modifiedParametersForLog);
audit.subscribeToService(dataManager, newSub);
logSubscriptionAttributeForCreation(newSub,
ParameterizedTypes.list(udas, VOUda.class),
originalCustomerUdas);
return newSub;
}
private void verifyUnitAndRoles(PlatformUser currentUser, UserGroup unit, Subscription newSub) throws OperationNotPermittedException {
if(!currentUser.isOrganizationAdmin()){
boolean isUnitAdmin = currentUser.isUnitAdmin();
boolean isSubMgr = currentUser.isSubscriptionManager();
boolean isUnitToBeAssigned = unit != null;
boolean unitIsMandatory = isUnitAdmin && !isSubMgr;
boolean unitIsForbidden = !isUnitAdmin && isSubMgr;
if (isUnitToBeAssigned && unitIsForbidden) {
throw new OperationNotPermittedException();
} else if (unitIsMandatory && !isUnitToBeAssigned) {
throw new OperationNotPermittedException();
}
}
if (currentUser.isOrganizationAdmin() || currentUser.isUnitAdmin()) {
newSub.setUserGroup(unit);
}
}
private void autoAssignUserForTriggerProcess(TriggerProcess tp,
VOService product, PlatformUser owner, Subscription newSub)
throws ObjectNotFoundException, OperationNotPermittedException,
ServiceParameterException, SubscriptionStateException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException, ConcurrentModificationException {
Product prod = dataManager
.getReference(Product.class, product.getKey());
TechnicalProduct techProd = prod.getTechnicalProduct();
if (ProvisioningType.SYNCHRONOUS.equals(techProd.getProvisioningType())
&& tp.getTriggerDefinition() != null
&& product.isAutoAssignUserEnabled().booleanValue()
&& newSub.getUsageLicenseForUser(owner) == null) {
// TODO 1. assign users only for SYNCHRONOUS case.
// 2. extract code to another method (more readability).
if (owner != dataManager.getCurrentUser()) {
assignUsersForSubscription(newSub.getSubscriptionId(), product,
owner);
} else {
assignUsersForSubscription(newSub.getSubscriptionId(), product);
}
}
}
List<VOUda> getUdasForCustomer(String targetType, long targetObjectKey,
Organization supplier) throws ValidationException,
ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("targetType", targetType);
UdaTargetType type = UdaAssembler.toUdaTargetType(targetType);
Organization customer = dataManager.getCurrentUser().getOrganization();
UdaAccess udaAccess = new UdaAccess(dataManager, sessionCtx);
List<Uda> udas = udaAccess.getUdasForTypeTargetAndCustomer(
targetObjectKey, type, supplier, customer);
List<VOUda> voUdas = new ArrayList<>();
for (Uda uda : udas) {
voUdas.add(UdaAssembler.toVOUda(uda));
}
return voUdas;
}
void logSubscriptionAttributeForEdit(Subscription sub, List<VOUda> udaList) {
Organization customer = dataManager.getCurrentUser().getOrganization();
for (VOUda voUda : udaList) {
audit.editSubscriptionAndCustomerAttributeByCustomer(dataManager,
customer, sub, voUda.getUdaDefinition().getUdaId(), voUda
.getUdaValue(), voUda.getUdaDefinition()
.getTargetType());
}
}
void logSubscriptionAttributeForCreation(Subscription sub,
List<VOUda> udaList, List<VOUda> customerUdaList) {
Map<String, String> customerAttributesMap = new HashMap<>();
for (VOUda voUda : customerUdaList) {
String parameterName = voUda.getUdaDefinition().getUdaId();
String parameterValue = voUda.getUdaValue();
customerAttributesMap.put(parameterName, parameterValue);
}
for (VOUda voUda : udaList) {
String parameterName = voUda.getUdaDefinition().getUdaId();
String targetType = voUda.getUdaDefinition().getTargetType();
String parameterValue = voUda.getUdaValue();
String defaultValue = voUda.getUdaDefinition().getDefaultValue();
defaultValue = defaultValue == null ? "" : defaultValue;
if (!UdaTargetType.CUSTOMER.toString().equals(targetType)) {
if (!parameterValue.equals(defaultValue)) {
audit.editSubscriptionAndCustomerAttributeByCustomer(
dataManager, null, sub, parameterName,
parameterValue, voUda.getUdaDefinition()
.getTargetType());
}
} else {
String existingValue = customerAttributesMap.get(voUda
.getUdaDefinition().getUdaId());
existingValue = existingValue == null ? "" : existingValue;
Organization customer = dataManager.getCurrentUser()
.getOrganization();
if (!(parameterValue.equals(existingValue) || parameterValue
.equals(defaultValue))) {
audit.editSubscriptionAndCustomerAttributeByCustomer(
dataManager, customer, null, parameterName,
parameterValue, voUda.getUdaDefinition()
.getTargetType());
}
}
}
}
void logSubscriptionOwner(Subscription sub, PlatformUser oldOwner) {
audit.editSubscriptionOwner(dataManager, sub, oldOwner);
}
/**
* Get the subscription attributes that are changed by user
*/
List<VOUda> getUpdatedSubscriptionAttributes(List<VOUda> inputUdaList,
List<Uda> existingUdas) {
Map<String, String> existingAttributesMap = new HashMap<>();
List<VOUda> updatedList = new ArrayList<>();
for (Uda uda : existingUdas) {
existingAttributesMap.put(uda.getUdaDefinition().getUdaId(),
uda.getUdaValue());
}
for (VOUda input : inputUdaList) {
String existingValue = existingAttributesMap.get(input
.getUdaDefinition().getUdaId());
String defaultValue = input.getUdaDefinition().getDefaultValue() == null ? ""
: input.getUdaDefinition().getDefaultValue();
String inputValue = input.getUdaValue() == null ? "" : input
.getUdaValue();
if (existingValue == null && !inputValue.equals(defaultValue)) {
updatedList.add(input);
}
if (existingValue != null && !inputValue.equals(existingValue)) {
updatedList.add(input);
}
}
return updatedList;
}
/**
* Enables the payment types that are enabled for new customer for the
* provided {@link OrganizationReference}.
*
* @param refSuplCust
* the reference to enable the default payment types for
*/
private void enableDefaultPaymentsForCustomer(
OrganizationReference refSuplCust) {
Organization supplier = refSuplCust.getSource();
Organization customer = refSuplCust.getTarget();
Set<OrganizationToRole> roles = customer.getGrantedRoles();
OrganizationRole role = null;
for (OrganizationToRole organizationToRole : roles) {
OrganizationRole tmp = organizationToRole.getOrganizationRole();
if (tmp.getRoleName() == OrganizationRoleType.CUSTOMER) {
role = tmp;
break;
}
}
// the suppliers default configuration
List<OrganizationRefToPaymentType> refs = supplier
.getPaymentTypes(
true,
refSuplCust.getReferenceType() == OrganizationReferenceType.RESELLER_TO_CUSTOMER ? OrganizationRoleType.RESELLER
: OrganizationRoleType.SUPPLIER,
OrganizationRoleType.PLATFORM_OPERATOR.name());
for (OrganizationRefToPaymentType ref : refs) {
OrganizationRefToPaymentType newRef = new OrganizationRefToPaymentType();
newRef.setOrganizationReference(refSuplCust);
newRef.setPaymentType(ref.getPaymentType());
newRef.setOrganizationRole(role);
try {
dataManager.persist(newRef);
} catch (NonUniqueBusinessKeyException e) {
SaaSSystemException sse = new SaaSSystemException(
"Caught NonUniqueBusinessKeyException although there is no business key",
e);
LOG.logError(Log4jLogger.SYSTEM_LOG, sse,
LogMessageIdentifier.ERROR_UNEXPECTED_BK_VIOLATION);
throw sse;
}
refSuplCust.getPaymentTypes().add(newRef);
}
}
/**
* Add users to the subscription assign the users to the subscription, but
* do not inform the product about it at this time (will be done later) We
* assume that the users already exist as platform users ! We start with the
* admins: if a user is in both lists, we just can ignore his entry in
* "users", as he is already entered from "admins" and has the correct
* isAdmin-flag ! We have to ensure that at least 1 user is assigned
*
* @throws ServiceParameterException
* @throws OperationNotPermittedException
* @throws ObjectNotFoundException
* @throws TechnicalServiceOperationException
* @throws TechnicalServiceNotAliveException
*/
private TenantProvisioningResult createInstanceAndAddUsersToSubscription(
TriggerProcess tp, Subscription subscription)
throws ServiceParameterException, ObjectNotFoundException,
OperationNotPermittedException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
List<PlatformUser> addedUsers = new ArrayList<>();
List<UsageLicense> addedUserLicenses = new ArrayList<>();
List<?> users = tp.getParamValueForName(
TriggerProcessParameterName.USERS).getValue(List.class);
if (users != null) {
for (Object o : users) {
VOUsageLicense lic = VOUsageLicense.class.cast(o);
PlatformUser usr = idManager.getPlatformUser(lic.getUser()
.getUserId(), true); // not found? => throws
// ObjectNotFoundException
RoleDefinition role = getAndCheckServiceRole(lic,
subscription.getProduct());
try {
addUserToSubscription(subscription, usr, role);
addedUsers.add(usr);
UsageLicense usageLicenseForUser = subscription
.getUsageLicenseForUser(usr);
// add the user's license to the list for later mail
// sending
if (usageLicenseForUser != null) {
addedUserLicenses.add(usageLicenseForUser);
}
} catch (UserAlreadyAssignedException e) {
// Most probably the user already has been in the users
// list (or he/she is in the list twice)
// Let's ignore it!
// But log this event !
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
LogMessageIdentifier.WARN_USER_APPEAR_MORE_THAN_ONCE,
Long.toString(usr.getKey()),
Long.toString(subscription.getKey()));
}
}
}
boolean directLogin = subscription.getProduct().getTechnicalProduct()
.getAccessType() == ServiceAccessType.DIRECT;
if (!directLogin) {
verifyParameterNamedUser(subscription);
}
// Call tenant provisioning to create instance! Afterwards the
// instance is started as well
TenantProvisioningResult provisioningResult = tenantProvisioning
.createProductInstance(subscription);
if (provisioningResult.isAsyncProvisioning()) {
return provisioningResult;
}
PriceModel pm = subscription.getProduct().getPriceModel();
pm.setProvisioningCompleted(true);
subscription.setActivationDate(subscription.getCreationDate());
activateSubscriptionFirstTime(subscription);
String instanceId = provisioningResult.getProductInstanceId();
subscription.setProductInstanceId(instanceId);
subscription.setAccessInfo(provisioningResult.getAccessInfo());
subscription.setBaseURL(provisioningResult.getBaseUrl());
subscription.setLoginPath(provisioningResult.getLoginPath());
// inform the product about the users
try {
informProductAboutNewUsers(subscription, addedUsers);
} catch (SubscriptionStateException e) {
// should never be reached because state is set to
// active
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_INFORM_PRODUCT_ABOUT_NEW_USER_FAILED);
}
// Send an email to the organization admin. Is performed
// after the save operation to ensure everything worked fine and
// no mail is sent if storing fails.
sendToSubscriptionAddedMail(subscription, addedUserLicenses);
return provisioningResult;
}
/**
* Send the subscription created email to the users assigned to the
* subscription. The mail also includes the access information.
*
* @param subscription
* the created subscription to get the id and access info (url or
* descriptive text) from
* @param usageLicenses
* the usage licenses of the users added to the subscription
*/
private void sendToSubscriptionAddedMail(Subscription subscription,
List<UsageLicense> usageLicenses) {
if (subscription.getStatus() != SubscriptionStatus.ACTIVE) {
return;
}
EmailType emailType = useAccessInfo(subscription) ? EmailType.SUBSCRIPTION_USER_ADDED_ACCESSTYPE_DIRECT
: EmailType.SUBSCRIPTION_USER_ADDED;
Long marketplaceKey = null;
if (subscription.getMarketplace() != null) {
marketplaceKey = Long.valueOf(subscription.getMarketplace()
.getKey());
}
SendMailPayload payload = new SendMailPayload();
for (UsageLicense usageLicense : usageLicenses) {
String accessInfo = getAccessInfo(subscription,
usageLicense.getUser());
if (isUsableAWSAccessInfo(accessInfo)) {
payload.addMailObjectForUser(usageLicense.getUser().getKey(),
EmailType.SUBSCRIPTION_USER_ADDED_ACCESSINFO,
new Object[] { subscription.getSubscriptionId(),
getPublicDNS(accessInfo),
getIPAddress(accessInfo),
getKeyPairName(accessInfo) }, marketplaceKey);
} else {
payload.addMailObjectForUser(usageLicense.getUser().getKey(),
emailType,
new Object[] { subscription.getSubscriptionId(),
accessInfo }, marketplaceKey);
}
}
TaskMessage message = new TaskMessage(SendMailHandler.class, payload);
tqs.sendAllMessages(Collections.singletonList(message));
}
private boolean useAccessInfo(Subscription subscription) {
ServiceAccessType accessType = subscription.getProduct()
.getTechnicalProduct().getAccessType();
return accessType == ServiceAccessType.DIRECT
|| accessType == ServiceAccessType.USER;
}
String getAccessInfo(Subscription subscription, PlatformUser user) {
String accessInfo;
if (useAccessInfo(subscription)) {
accessInfo = subscription.getAccessInfo();
if (accessInfo == null) {
accessInfo = localizer.getLocalizedTextFromDatabase(
user.getLocale(), subscription.getProduct()
.getTechnicalProduct().getKey(),
LocalizedObjectTypes.TEC_PRODUCT_LOGIN_ACCESS_DESC);
if (accessInfo != null) {
accessInfo = accessInfo.replaceAll("<p>", "\n");
accessInfo = accessInfo.replaceAll("</p>", "\n");
}
}
} else {
accessInfo = getSubscriptionUrl(subscription);
}
if (accessInfo == null) {
accessInfo = "";
}
return accessInfo;
}
/**
* Gets the URL to access the subscription.
*
* @param subscription
* the subscription for which we want to know the URL
* @return the URL to access the subscription
*/
String getSubscriptionUrl(Subscription subscription) {
StringBuilder url = new StringBuilder();
String baseUrl = cfgService.getBaseURL();
String technicalProductBaseUrl = subscription.getProduct()
.getTechnicalProduct().getBaseURL();
if (ADMValidator.isHttpsScheme(technicalProductBaseUrl)) {
baseUrl = cfgService.getConfigurationSetting(
ConfigurationKey.BASE_URL_HTTPS,
Configuration.GLOBAL_CONTEXT).getValue();
}
url.append(baseUrl);
if (url.length() == 0 || url.charAt(url.length() - 1) != '/') {
url.append('/');
}
url.append("opt/");
url.append(Long.toHexString(subscription.getKey()));
url.append('/');
return url.toString();
}
/**
* Creates the 'allowing on behalf acting reference' between the technology
* provider and the customer's organization.
*
* @throws NonUniqueBusinessKeyException
*/
private void createAllowOnBehalfActingReference(Subscription subscription)
throws NonUniqueBusinessKeyException {
// fetch the technical product
TechnicalProduct technicalProduct = subscription.getProduct()
.getTechnicalProduct();
// if allow on behalf acting is true
if (technicalProduct.isAllowingOnBehalfActing()) {
// get source (techn. prov.) and target (supplier) organization
Organization source = technicalProduct.getOrganization();
Organization target = dataManager.getCurrentUser()
.getOrganization();
// check if a reference does not already exist
if (!isOnBehalfReferenceExisting(source, target)) {
// create and persist reference
OrganizationReference reference = new OrganizationReference(
source, target,
OrganizationReferenceType.ON_BEHALF_ACTING);
dataManager.persist(reference);
}
}
}
private boolean isOnBehalfReferenceExisting(
Organization sourceOrganization, Organization targetOrganization) {
return getOrganizationReference(sourceOrganization, targetOrganization) != null;
}
private OrganizationReference getOrganizationReference(
Organization sourceOrganization, Organization targetOrganization) {
for (OrganizationReference reference : targetOrganization
.getSourcesForType(OrganizationReferenceType.ON_BEHALF_ACTING)) {
if (reference.getSource().getKey() == sourceOrganization.getKey()
&& reference.getTargetKey() == targetOrganization.getKey()) {
return reference;
}
}
return null;
}
private void sendSubscriptionCreatedMailToAdministrators(
Subscription subscription, boolean actingOnBehalf) {
EmailType emailType = actingOnBehalf ? EmailType.SUBSCRIPTION_CREATED_ON_BEHALF_ACTING
: EmailType.SUBSCRIPTION_CREATED;
Long marketplaceKey = null;
if (subscription.getMarketplace() != null) {
marketplaceKey = Long.valueOf(subscription.getMarketplace()
.getKey());
}
SendMailPayload payload = new SendMailPayload();
List<PlatformUser> users = manageBean
.getCustomerAdminsAndSubscriptionOwner(subscription);
for (PlatformUser user : users) {
payload.addMailObjectForUser(user.getKey(), emailType,
new Object[] { subscription.getSubscriptionId() },
marketplaceKey);
}
TaskMessage message = new TaskMessage(SendMailHandler.class, payload);
tqs.sendAllMessages(Collections.singletonList(message));
}
/**
* Validates that subscribing to the given product is possible with the
* specified subscription data.
*
* @param subscription
* The subscription to be created.
* @param product
* The product to subscribe to.
* @param voBillingContact
* @throws ValidationException
* Thrown in case the validation of the subscription failed.
* @throws ObjectNotFoundException
* Thrown in case the product could not be found.
* @throws OperationNotPermittedException
* Thrown in case the user is not permitted to perform this
* operation.
* @throws ServiceChangedException
* Thrown in case the product has been modified in the meantime.
* @throws PriceModelException
* Thrown in case the product is not useable as it has no price
* model.
* @throws PaymentInformationException
* Thrown in case the product is chargeable but the customer
* does not have a payment information stored.
* @throws ConcurrentModificationException
*/
private void validateSettingsForSubscribing(VOSubscription subscription,
VOService product, VOPaymentInfo paymentInfo,
VOBillingContact voBillingContact) throws ValidationException,
ObjectNotFoundException, OperationNotPermittedException,
ServiceChangedException, PriceModelException,
PaymentInformationException, ConcurrentModificationException {
String subscriptionId = subscription.getSubscriptionId();
BLValidator.isId("subscriptionId", subscriptionId, true);
String pon = subscription.getPurchaseOrderNumber();
BLValidator.isDescription("purchaseOrderNumber", pon, false);
Product productTemplate = dataManager.getReference(Product.class,
product.getKey());
// check product and org settings
Organization targetCustomer = productTemplate.getTargetCustomer();
PlatformUser currentUser = dataManager.getCurrentUser();
Organization organization = currentUser.getOrganization();
if (targetCustomer == null) {
// if it is no customer specific product, check if we have one
// for the subscriber
List<Product> resultList = getProductDao().getCopyForCustomer(
productTemplate, organization);
if (resultList.size() > 0) {
ServiceChangedException sce = new ServiceChangedException(
ServiceChangedException.Reason.SERVICE_MODIFIED);
LOG.logWarn(
Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
sce,
LogMessageIdentifier.WARN_CUSTOMER_MUST_SUBSCRIBE_SPECIFIC_PRODUCT,
organization.getOrganizationId(), productTemplate
.getProductId(), resultList.get(0)
.getProductId());
throw sce;
}
} else if (organization.getKey() != targetCustomer.getKey()) {
// if it is a specific one but not specified for the subscriber
String message = String
.format("Customer specific product '%s' is not specified for customer '%s'.",
productTemplate.getProductId(),
organization.getOrganizationId());
OperationNotPermittedException onp = new OperationNotPermittedException(
message);
LOG.logWarn(
Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
onp,
LogMessageIdentifier.WARN_CUSTOMER_SPECIFIC_PRODUCT_NOT_FOR_THE_CUSTOMER,
productTemplate.getProductId(),
organization.getOrganizationId());
throw onp;
}
checkIfProductIsUptodate(productTemplate, product);
// now check the price model related to the product; if it is
// chargeable, the organization must have specified a payment
// information. If he has not, throw an exception
PriceModel priceModel = productTemplate.getPriceModel();
if (priceModel == null
&& productTemplate.getType() == ServiceType.PARTNER_TEMPLATE) {
priceModel = productTemplate.getTemplate().getPriceModel();
}
if (priceModel == null) {
PriceModelException mpme = new PriceModelException(
PriceModelException.Reason.NOT_DEFINED);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, mpme,
LogMessageIdentifier.WARN_SUBSCRIBE_PRODUCT_FAILED,
Long.toString(productTemplate.getKey()));
throw mpme;
}
if (priceModel.isChargeable()) {
PaymentDataValidator.validateNotNull(paymentInfo, voBillingContact);
PaymentInfo pi = dataManager.getReference(PaymentInfo.class,
paymentInfo.getKey());
BillingContact bc = dataManager.getReference(BillingContact.class,
voBillingContact.getKey());
validatePaymentInfoAndBillingContact(pi, bc, paymentInfo,
voBillingContact);
PermissionCheck.owns(pi, organization, LOG);
PermissionCheck.owns(bc, organization, LOG);
PaymentDataValidator.validatePaymentTypeSupportedBySupplier(
organization, productTemplate, pi.getPaymentType());
PaymentDataValidator.validatePaymentInfoDataForUsage(pi);
}
}
UserGroup getUnit(long unitKey, String unitName, long organizationKey)
throws ObjectNotFoundException {
UserGroup unit = null;
if (unitKey == 0L) {
if (unitName == null || unitName.trim().length() == 0) {
return null;
}
unit = new UserGroup();
unit.setName(unitName);
unit.setOrganization_tkey(organizationKey);
unit = (UserGroup) dataManager.getReferenceByBusinessKey(unit);
} else {
try {
unit = dataManager.getReference(UserGroup.class, unitKey);
if (unit.getOrganization_tkey() != organizationKey) {
throw new ObjectNotFoundException(
"The unit does not belong to your organization.");
}
} catch (ObjectNotFoundException e) {
e.setMessageParams(new String[] { unitName });
throw e;
}
}
return unit;
}
private void checkIfServiceAvailable(long productKey, String productId,
PlatformUser currentUser) throws OperationNotPermittedException,
ObjectNotFoundException {
if (currentUser.isOrganizationAdmin()) {
return;
}
List<Long> invisibleProductKeys = userGroupService
.getInvisibleProductKeysForUser(currentUser.getKey());
if (invisibleProductKeys.contains(Long.valueOf(productKey))) {
String message = String.format("Service '%s' is not avalible.",
productId);
OperationNotPermittedException onp = new OperationNotPermittedException(
message);
LOG.logWarn(Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG, onp,
LogMessageIdentifier.WARN_SERVICE_NOT_AVAILABLE, productId);
throw onp;
}
}
/**
* Checks if there already exists a subscription to the technical service to
* which the specified VOService belongs to.
*
* @param product
* the VOService for which to check if already has active
* subscriptions.
*/
private void checkIfSubscriptionAlreadyExists(VOService product)
throws SubscriptionAlreadyExistsException, ObjectNotFoundException {
// Fetch the technical product to which the defined product belongs to.
Product prod = dataManager
.getReference(Product.class, product.getKey());
TechnicalProduct technicalProduct = prod.getTechnicalProduct();
// Only in case one subscription is allowed check the number of already
// existing subscriptions.
if (technicalProduct.isOnlyOneSubscriptionAllowed()) {
Organization organization = dataManager.getCurrentUser()
.getOrganization();
Long numberOfSubscriptions = getSubscriptionDao()
.getNumberOfVisibleSubscriptions(technicalProduct,
organization);
// If there are already subscriptions to the technical product
// based on the product, throw an exception.
if (numberOfSubscriptions.longValue() > 0) {
Object[] params = new Object[] { prod.getProductId() };
SubscriptionAlreadyExistsException subAlreadyExistsException = new SubscriptionAlreadyExistsException(
params);
LOG.logWarn(
Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
subAlreadyExistsException,
LogMessageIdentifier.WARN_USER_SUBSCRIBE_SERVICE_FAILED_ONLY_ONE_ALLOWED,
Long.toString(dataManager.getCurrentUser().getKey()),
Long.toString(prod.getKey()),
Long.toString(organization.getKey()));
throw subAlreadyExistsException;
}
}
}
/**
* Checks if there already exists a subscription with the same subscriptions
* name for this Organization.
*
* @param currentUser
* current platform user
* @param voSubscription
* subscription
* @throws NonUniqueBusinessKeyException
*/
private void verifyIdAndKeyUniqueness(PlatformUser currentUser,
VOSubscription voSubscription) throws NonUniqueBusinessKeyException {
Subscription newSubscription = new Subscription();
newSubscription.setOrganizationKey(currentUser.getOrganization()
.getKey());
newSubscription.setSubscriptionId(voSubscription.getSubscriptionId());
dataManager.validateBusinessKeyUniqueness(newSubscription);
}
/**
* Its responsible for updating the values for the subscribed product from
* the parameter list.
*
* @param product
* the product to update
* @param parameters
* the list of parameters
* @param subscription
* - target subscription
*/
List<Parameter> updateConfiguredParameterValues(Product product,
List<VOParameter> parameters, Subscription subscription) {
Map<String, Parameter> paramMap = new HashMap<>();
if (product.getParameterSet() != null) {
for (Parameter parameter : product.getParameterSet()
.getParameters()) {
paramMap.put(parameter.getParameterDefinition()
.getParameterId(), parameter);
}
}
// reload all the parameter values from old subscription
if (subscription != null && subscription.getParameterSet() != null
&& !subscription.getProduct().equals(product)) {
List<Parameter> params = subscription.getParameterSet()
.getParameters();
if (params != null && params.size() > 0) {
for (Parameter param : params) {
String parameterId = param.getParameterDefinition()
.getParameterId();
Parameter uParam = paramMap.get(parameterId);
if (uParam != null) {
uParam.setValue(param.getValue());
}
}
}
}
List<Parameter> modifiedParametesForLog = new ArrayList<>();
for (VOParameter voParameter : parameters) {
String parameterID = voParameter.getParameterDefinition()
.getParameterId();
Parameter param = paramMap.get(parameterID);
if (param != null) {
String oldValue = param.getValue();
param.setValue(voParameter.getValue());
String defaultValue = param.getParameterDefinition()
.getDefaultValue();
if ((oldValue != null && !oldValue.equals(param.getValue()))
|| (oldValue == null && param.getValue() != null && !param
.getValue().equals(defaultValue))) {
modifiedParametesForLog.add(param);
}
}
}
dataManager.flush();
return modifiedParametesForLog;
}
/**
* If a product with a customer specific price model, was copied the
* subscription specific one would refer to the template's one when getting
* localized values - so we have to copy those ones from the original price
* model
*
* @param targetProduct
* @param sourceProduct
*/
private void copyLocalizedPricemodelValues(Product targetProduct,
Product sourceProduct) {
List<VOLocalizedText> localizedValues;
final PriceModel priceModelTarget = targetProduct.getPriceModel();
final PriceModel priceModelSource = sourceProduct.getType() == ServiceType.PARTNER_TEMPLATE ? sourceProduct
.getTemplate().getPriceModel() : sourceProduct.getPriceModel();
if ((priceModelTarget != null) && (priceModelSource != null)) {
long targetKey = targetProduct.getPriceModel().getKey();
long sourceKey = priceModelSource.getKey();
localizedValues = localizer.getLocalizedValues(sourceKey,
LocalizedObjectTypes.PRICEMODEL_DESCRIPTION);
if (localizedValues != null && !localizedValues.isEmpty()) {
localizer.storeLocalizedResources(targetKey,
LocalizedObjectTypes.PRICEMODEL_DESCRIPTION,
localizedValues);
}
// license copy
if (sourceProduct.getVendor().getGrantedRoleTypes()
.contains(OrganizationRoleType.RESELLER)) {
localizedValues = localizer.getLocalizedValues(
sourceProduct.getKey(),
LocalizedObjectTypes.RESELLER_PRICEMODEL_LICENSE);
} else {
localizedValues = localizer.getLocalizedValues(sourceKey,
LocalizedObjectTypes.PRICEMODEL_LICENSE);
}
if (localizedValues != null && !localizedValues.isEmpty()) {
localizer.storeLocalizedResources(targetKey,
LocalizedObjectTypes.PRICEMODEL_LICENSE,
localizedValues);
}
}
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public boolean addRevokeUser(String subscriptionId,
List<VOUsageLicense> usersToBeAdded, List<VOUser> usersToBeRevoked)
throws ObjectNotFoundException, ServiceParameterException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationNotPermittedException,
ConcurrentModificationException, OperationPendingException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
Subscription sub = manageBean.checkSubscriptionOwner(subscriptionId, 0);
stateValidator.checkAddRevokeUserAllowed(sub);
// validation
if (usersToBeAdded != null) {
for (VOUsageLicense lic : usersToBeAdded) {
try {
PlatformUser user = dataManager.getReference(
PlatformUser.class, lic.getUser().getKey());
getAndCheckServiceRole(lic, sub.getProduct());
// fill user ID for trigger process
lic.getUser().setUserId(user.getUserId());
} catch (ObjectNotFoundException e) {
throw new ObjectNotFoundException(
DomainObjectException.ClassEnum.USER,
String.valueOf(lic.getUser().getUserId()));
}
}
}
if (usersToBeRevoked != null) {
for (VOUser entry : usersToBeRevoked) {
try {
PlatformUser user = dataManager.getReference(
PlatformUser.class, entry.getKey());
// fill user ID for trigger process
entry.setUserId(user.getUserId());
} catch (ObjectNotFoundException e) {
throw new ObjectNotFoundException(
DomainObjectException.ClassEnum.USER,
String.valueOf(entry.getUserId()));
}
}
}
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
List<TriggerProcessIdentifier> pendingAddRevokeUsers = validator
.getPendingAddRevokeUsers(subscriptionId, usersToBeAdded,
usersToBeRevoked);
if (!pendingAddRevokeUsers.isEmpty()) {
String userIds = determineUserIds(pendingAddRevokeUsers);
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request for subscription '%s' to add or revoke the users: %s",
subscriptionId, userIds),
ReasonEnum.ADD_REVOKE_USER, new Object[] { subscriptionId,
userIds });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_ADD_REVOKE_USER_FAILED_DUE_TO_TRIGGER_CONFLICT,
subscriptionId);
throw ope;
}
validateTriggerProcessForSubscription(sub);
// now send a suspending message for the processing
TriggerMessage message = new TriggerMessage(TriggerType.ADD_REVOKE_USER);
List<TriggerProcessMessageData> list = triggerQS
.sendSuspendingMessages(Collections.singletonList(message));
TriggerProcess proc = list.get(0).getTrigger();
proc.addTriggerProcessParameter(TriggerProcessParameterName.OBJECT_ID,
subscriptionId);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscriptionId);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.USERS_TO_ADD, usersToBeAdded);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.USERS_TO_REVOKE, usersToBeRevoked);
try {
// if processing is not suspended, call finishing method
TriggerDefinition triggerDefinition = proc.getTriggerDefinition();
if (triggerDefinition == null) {
addRevokeUserInt(proc);
return true;
} else if (triggerDefinition.isSuspendProcess()) {
proc.setTriggerProcessIdentifiers(TriggerProcessIdentifiers
.createAddRevokeUser(dataManager,
TriggerType.ADD_REVOKE_USER, subscriptionId,
usersToBeAdded, usersToBeRevoked));
dataManager.merge(proc);
}
} catch (ObjectNotFoundException | SubscriptionStateException
| TechnicalServiceNotAliveException
| TechnicalServiceOperationException e) {
sessionCtx.setRollbackOnly();
throw e;
}
return false;
}
void validateTriggerProcessForSubscription(Subscription subscription)
throws OperationPendingException {
validateTriggerProcessForUnsubscribeFromService(subscription
.getSubscriptionId());
validateTriggerProcessForUpgradeSubscriptionBySubscriptionKey(
subscription.getKey(), subscription.getSubscriptionId());
validateTriggerProcessForModifySubscriptionBySubscriptionKey(
subscription.getKey(), subscription.getSubscriptionId());
}
/**
* Determines the user identifiers that are contained in the passed in list
* of process identifiers.
*
* @param pendingAddRevokeUsers
* The list of process identifiers to check.
* @return The user identifiers.
*/
private String determineUserIds(
List<TriggerProcessIdentifier> pendingAddRevokeUsers) {
StringBuilder userIds = new StringBuilder();
for (TriggerProcessIdentifier id : pendingAddRevokeUsers) {
if (userIds.length() != 0) {
userIds.append(", ");
}
if (TriggerProcessIdentifierName.USER_TO_ADD.equals(id.getName())
|| TriggerProcessIdentifierName.USER_TO_REVOKE.equals(id
.getName())) {
userIds.append(id.getValue());
}
}
return userIds.toString();
}
/**
* Tries to read the service role that should be assigned (if not
* <code>null</code>). If the role exists, it will be checked if it belongs
* to the product's technical product.
*
* @param lic
* the {@link VOUsageLicense}
* @param prod
* the {@link Product}
* @return <code>null</code> if no service roles are defined on the
* technical product and the specified one on the
* {@link VOUsageLicense} is <code>null</code>. Otherwise the read
* role will be returned if valid
* @throws ObjectNotFoundException
* in case the role wasn't found.
* @throws OperationNotPermittedException
* in case the read role doesn't belong to the subscriptions
* technical product or no role is specified when service roles
* have to be used on the technical product
*/
private RoleDefinition getAndCheckServiceRole(VOUsageLicense lic,
Product prod) throws ObjectNotFoundException,
OperationNotPermittedException {
TechnicalProduct tp = prod.getTechnicalProduct();
List<RoleDefinition> roles = tp.getRoleDefinitions();
if (roles == null || roles.isEmpty()) {
lic.setRoleDefinition(null);
return null;
}
if (lic.getRoleDefinition() == null) {
String message = "User assignment to technical service '%s' without service role not possible.";
OperationNotPermittedException onp = new OperationNotPermittedException(
String.format(message, Long.valueOf(tp.getKey())));
LOG.logError(
Log4jLogger.SYSTEM_LOG,
onp,
LogMessageIdentifier.ERROR_USER_ASSIGNMENT_TO_TECHNICAL_SERVICE_FAILED_NO_SERVICE_ROLE,
Long.toString(tp.getKey()));
throw onp;
}
RoleDefinition role = dataManager.getReference(RoleDefinition.class,
lic.getRoleDefinition().getKey());
for (RoleDefinition roleDefinition : roles) {
if (role.getKey() == roleDefinition.getKey()) {
return role;
}
}
String message = "Role '%s' is not defined on technical service '%s'";
OperationNotPermittedException onp = new OperationNotPermittedException(
String.format(message, Long.valueOf(role.getKey()),
Long.valueOf(tp.getKey())));
LOG.logError(Log4jLogger.SYSTEM_LOG, onp,
LogMessageIdentifier.ERROR_NO_ROLE_FOR_TECHNICAL_SERVICE,
Long.toString(role.getKey()), Long.toString(tp.getKey()));
throw onp;
}
@Override
@RolesAllowed("ORGANIZATION_ADMIN")
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void addRevokeUserInt(TriggerProcess tp)
throws ObjectNotFoundException, ServiceParameterException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationNotPermittedException,
ConcurrentModificationException {
TriggerProcessParameter mod;
mod = tp.getParamValueForName(TriggerProcessParameterName.SUBSCRIPTION);
String subscriptionId = mod.getValue(String.class);
mod = tp.getParamValueForName(TriggerProcessParameterName.USERS_TO_ADD);
List<?> usersToBeAdded = mod.getValue(List.class);
mod = tp.getParamValueForName(TriggerProcessParameterName.USERS_TO_REVOKE);
List<?> usersToBeRevoked = mod.getValue(List.class);
// Try to find the subscription
Subscription subscription = manageBean.loadSubscription(subscriptionId,
0);
List<UsageLicense> addedUsersLicenses = new ArrayList<>();
List<PlatformUser> usersToAdd = new ArrayList<>();
// loop for adding users
if (usersToBeAdded != null) {
for (Object entry : usersToBeAdded) {
final VOUsageLicense lic = (VOUsageLicense) entry;
final PlatformUser usr = dataManager.getReference(
PlatformUser.class, lic.getUser().getKey());
final RoleDefinition roleDef = getAndCheckServiceRole(lic,
subscription.getProduct());
final UsageLicense usageLicenseForUser = subscription
.getUsageLicenseForUser(usr);
try {
if (usageLicenseForUser == null) {
// Create a new usage License
final UsageLicense newUsageLicense = addUserToSubscription(
subscription, usr, roleDef);
usersToAdd.add(usr);
// store the new user's licenses for later mail sending
addedUsersLicenses.add(newUsageLicense);
} else {
// Update an existing usage license:
BaseAssembler.verifyVersionAndKey(usageLicenseForUser,
lic);
modifyUserRole(subscription, usr, roleDef);
}
} catch (UserNotAssignedException
| UserAlreadyAssignedException e) {
// Must not happen here
throw new AssertionError(e);
}
}
}
// loop for revoking users
if (usersToBeRevoked != null) {
List<PlatformUser> platformUsers = new ArrayList<>();
for (Object qryUsr : usersToBeRevoked) {
PlatformUser usr = dataManager.getReference(PlatformUser.class,
VOUser.class.cast(qryUsr).getKey());
platformUsers.add(usr);
}
revokeUserFromSubscription(subscription, platformUsers);
}
verifyParameterNamedUser(subscription);
informProductAboutNewUsers(subscription, usersToAdd);
sendToSubscriptionAddedMail(subscription, addedUsersLicenses);
// notify all listeners
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.ADD_REVOKE_USER, tp.getTriggerProcessParameters(),
dataManager.getCurrentUser().getOrganization()));
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void modifyUserRole(Subscription subscription, PlatformUser usr,
RoleDefinition roleDef) throws SubscriptionStateException,
UserNotAssignedException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
stateValidator.checkModifyUserRoleAllowed(subscription);
UsageLicense license = subscription.getUsageLicenseForUser(usr);
RoleDefinition oldRoleDef = null;
if (license != null) {
oldRoleDef = license.getRoleDefinition();
if (oldRoleDef == roleDef) {
// nothing to do - role not changed; avoid sending of mail and
// notification of service
return;
}
}
UsageLicense targetLicense = subscription.changeRole(usr, roleDef);
// Inform application about changed role
if (canModifyApplicationUsers(subscription) && targetLicense != null) {
appManager.updateUsers(subscription,
Collections.singletonList(targetLicense));
// log deassign user role for service
audit.deassignUserRoleForService(dataManager, subscription, usr,
oldRoleDef);
// log assign user role for service
audit.assignUserRoleForService(dataManager, subscription, usr,
roleDef);
}
try {
String accessInfo = targetLicense == null ? "" : getAccessInfo(
subscription, targetLicense.getUser());
commService
.sendMail(usr, EmailType.SUBSCRIPTION_ACCESS_GRANTED,
new Object[] { subscription.getSubscriptionId(),
accessInfo }, subscription.getMarketplace());
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_GRANT_ROLE_IN_SUBSCRIPTION_CONFIRMING_FAILED);
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public UsageLicense addUserToSubscription(Subscription subscription,
PlatformUser user, RoleDefinition serviceRole)
throws UserAlreadyAssignedException {
final UsageLicense usageLicense = subscription.addUser(user,
serviceRole);
audit.assignUserToSubscription(dataManager, subscription, usageLicense);
return usageLicense;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void revokeUserFromSubscription(final Subscription subscription,
final List<PlatformUser> users) throws SubscriptionStateException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
stateValidator.checkAddRevokeUserAllowed(subscription);
revokeUserFromSubscriptionInt(subscription, users);
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void revokeUserFromSubscriptionInt(final Subscription subscription,
final List<PlatformUser> users)
throws TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
List<UsageLicense> usageLicenses = doRevokeUserFromSubscriptionInt(
subscription, users);
audit.deassignUserFromSubscription(dataManager, subscription,
usageLicenses);
}
/**
* Worker method for revokeUserFromSubscription, allows to ignore
* lastUser-Check (only for use in unsubscribe)
*
* @param subscription
* The subscription to be changed.
* @param users
* The users to be revoked from the subscription.
* @return the list of usage licenses
* @throws TechnicalServiceNotAliveException
* @throws TechnicalServiceOperationException
*/
private List<UsageLicense> doRevokeUserFromSubscriptionInt(
Subscription subscription, List<PlatformUser> users)
throws TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
List<UsageLicense> licenseList = new ArrayList<>();
for (PlatformUser user : users) {
UsageLicense license = subscription.revokeUser(user);
// if the subscription is invalid (e.g. instance creation
// failed) no call to the application is performed
if (isValidSubscription(subscription) && license != null) {
licenseList.add(license);
}
}
// Bug 9998. while the subscription is still pending, no call to
// ProvisioningService.deleteUsers(String, List<User>) has to be
// performed.
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
appManager.deleteUsers(subscription, licenseList);
}
for (UsageLicense license : licenseList) {
// explicitly remove the user's usage license
if (license != null) {
dataManager.remove(license);
}
dataManager.flush();
}
if (subscription.getStatus() == SubscriptionStatus.ACTIVE
&& subscription.getProduct().getTechnicalProduct()
.getAccessType() != ServiceAccessType.DIRECT) {
// as the user gets no mail when being added to a pending
// subscription, the notification about the removal will also not be
// sent.
Long marketplaceKey = null;
if (subscription.getMarketplace() != null) {
marketplaceKey = Long.valueOf(subscription.getMarketplace()
.getKey());
}
SendMailPayload payload = new SendMailPayload();
for (PlatformUser user : users) {
payload.addMailObjectForUser(user.getKey(),
EmailType.SUBSCRIPTION_USER_REMOVED,
new Object[] { subscription.getSubscriptionId() },
marketplaceKey);
}
TaskMessage message = new TaskMessage(SendMailHandler.class,
payload);
tqs.sendAllMessages(Collections.singletonList(message));
}
return licenseList;
}
private boolean isValidSubscription(Subscription subscription) {
return subscription.getStatus() != SubscriptionStatus.INVALID;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<Subscription> getSubscriptionsForUserInt(PlatformUser user) {
return getSubscriptionDao().getSubscriptionsForUser(user);
}
@Override
@RolesAllowed("ORGANIZATION_ADMIN")
public List<VOUserSubscription> getSubscriptionsForUser(VOUser user)
throws ObjectNotFoundException, OperationNotPermittedException {
return getSubscriptionsForUser(user, PerformanceHint.ALL_FIELDS);
}
@RolesAllowed("ORGANIZATION_ADMIN")
public List<VOUserSubscription> getSubscriptionsForUser(VOUser user,
PerformanceHint performanceHint) throws ObjectNotFoundException,
OperationNotPermittedException {
ArgumentValidator.notNull("user", user);
PlatformUser platformUser = idManager.getPlatformUser(user.getUserId(),
true);
LocalizerFacade facade = new LocalizerFacade(localizer,
platformUser.getLocale());
List<Subscription> subs = getSubscriptionsForUserInt(platformUser);
ArrayList<VOUserSubscription> result = new ArrayList<>();
for (Subscription sub : subs) {
VOUserSubscription voSub = SubscriptionAssembler
.toVOUserSubscription(sub, platformUser, facade,
performanceHint);
result.add(voSub);
}
return result;
}
@Override
public List<VOUserSubscription> getSubscriptionsForCurrentUser() {
ArrayList<VOUserSubscription> result = new ArrayList<>();
PlatformUser user = dataManager.getCurrentUser();
List<Subscription> subs = getSubscriptionsForUserInt(user);
LocalizerFacade facade = new LocalizerFacade(localizer,
user.getLocale());
SubscriptionAssembler.prefetchData(subs, facade);
for (Subscription sub : subs) {
VOUserSubscription voSub = SubscriptionAssembler
.toVOUserSubscription(sub, user, facade);
result.add(voSub);
}
return result;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VOSubscription> getSubscriptionsForOrganization() {
return getSubscriptionsForOrganizationWithFilter(null);
}
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VOSubscription> getSubscriptionsForOrganization(
PerformanceHint performanceHint) {
return getSubscriptionsForOrganizationWithFilter(null, performanceHint);
}
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER", "UNIT_ADMINISTRATOR" })
public List<VOSubscription> getAllSubscriptionsForOrganization(
PerformanceHint performanceHint) {
ArrayList<VOSubscription> result = new ArrayList<>();
List<Subscription> subscriptions = subscriptionListService
.getAllSubscriptionsForOrganization();
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
for (Subscription sub : subscriptions) {
VOSubscription voSub = SubscriptionAssembler.toVOSubscription(sub,
facade, performanceHint);
result.add(voSub);
}
return result;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VOSubscription> getSubscriptionsForOrganizationWithFilter(
Set<SubscriptionStatus> requiredStatus) {
return getSubscriptionsForOrganizationWithFilter(requiredStatus,
PerformanceHint.ALL_FIELDS);
}
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VOSubscription> getSubscriptionsForOrganizationWithFilter(
Set<SubscriptionStatus> requiredStatus,
PerformanceHint performanceHint) {
ArrayList<VOSubscription> result = new ArrayList<>();
// load all subscriptions
List<Subscription> subs = subscriptionListService
.getSubscriptionsForOrganization(requiredStatus);
// create transfer objects
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
for (Subscription sub : subs) {
VOSubscription voSub = SubscriptionAssembler.toVOSubscription(sub,
facade, performanceHint);
result.add(voSub);
}
return result;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public boolean validateSubscriptionIdForOrganization(String subscriptionId) {
// load all subscriptions
List<Subscription> subs = subscriptionListService
.getSubscriptionsForOrganization(null);
boolean subscriptionIdAlreadyExists = false;
for (Subscription sub : subs) {
if (sub.getSubscriptionId().equals(subscriptionId)) {
subscriptionIdAlreadyExists = true;
break;
}
}
return subscriptionIdAlreadyExists;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public VOSubscriptionDetails getSubscriptionDetails(String subscriptionId)
throws ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
Subscription subscription = manageBean.checkSubscriptionOwner(
subscriptionId, 0);
return getSubscriptionDetails(subscription);
}
@Override
public VOSubscriptionDetails getSubscriptionDetails(long subscriptionKey)
throws ObjectNotFoundException, OperationNotPermittedException {
Subscription subscription = manageBean.checkSubscriptionOwner(null,
subscriptionKey);
return getSubscriptionDetails(subscription);
}
private VOSubscriptionDetails getSubscriptionDetails(
Subscription subscription) {
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
return SubscriptionAssembler.toVOSubscriptionDetails(subscription,
facade);
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public boolean unsubscribeFromService(String subscriptionId)
throws ObjectNotFoundException, SubscriptionStillActiveException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationPendingException,
OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
manageBean.checkSubscriptionOwner(subscriptionId, 0);
// Find the subscription and validate if operation can be performed
validateSubsciptionForUnsubscribe(subscriptionId);
validateTriggerProcessForUnsubscribeFromService(subscriptionId);
TriggerProcess triggerProcess = createTriggerProcessForUnsubscribeFromService(subscriptionId);
TriggerDefinition triggerDefinition = triggerProcess
.getTriggerDefinition();
if (triggerDefinition == null) {
try {
unsubscribeFromServiceInt(triggerProcess);
return true;
} catch (ObjectNotFoundException | SubscriptionStillActiveException
| SubscriptionStateException
| TechnicalServiceNotAliveException
| TechnicalServiceOperationException e) {
sessionCtx.setRollbackOnly();
throw e;
}
} else if (triggerDefinition.isSuspendProcess()) {
triggerProcess
.setTriggerProcessIdentifiers(TriggerProcessIdentifiers
.createUnsubscribeFromService(dataManager,
TriggerType.UNSUBSCRIBE_FROM_SERVICE,
subscriptionId));
dataManager.merge(triggerProcess);
}
return false;
}
/**
* @param subscriptionId
* @return
*/
private TriggerProcess createTriggerProcessForUnsubscribeFromService(
String subscriptionId) {
TriggerMessage message = new TriggerMessage(
TriggerType.UNSUBSCRIBE_FROM_SERVICE);
List<TriggerProcessMessageData> list = triggerQS
.sendSuspendingMessages(Collections.singletonList(message));
TriggerProcess triggerProcess = list.get(0).getTrigger();
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.OBJECT_ID, subscriptionId);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscriptionId);
return triggerProcess;
}
private void validateTriggerProcessForUnsubscribeFromService(
String subscriptionId) throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
if (validator.isSubscribeOrUnsubscribeServicePending(subscriptionId)) {
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to unsubscribe from the subscription or create a subscription with identifier '%s'",
subscriptionId),
ReasonEnum.UNSUBSCRIBE_FROM_SERVICE,
new Object[] { subscriptionId });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_UNSUBSCRIBE_FROM_SERVICE_FAILED_DUE_TO_TRIGGER_CONFLICT,
subscriptionId);
throw ope;
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void unsubscribeFromServiceInt(TriggerProcess tp)
throws ObjectNotFoundException, SubscriptionStateException,
SubscriptionStillActiveException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
String subId = tp.getParamValueForName(
TriggerProcessParameterName.SUBSCRIPTION)
.getValue(String.class);
Subscription subscription = validateSubsciptionForUnsubscribe(subId);
stopInstance(subscription);
unsubscribe(subscription);
manageBean.removeUsageLicenses(subscription);
operationRecordBean.removeOperationsForSubscription(subscription
.getKey());
// rename the subscription as last step because id is still used for
// exceptions and mails rename to allow the reuse of the id
final String oldSubscriptionId = subscription.getSubscriptionId();
subscription.setSubscriptionId(String.valueOf(System
.currentTimeMillis()));
boolean removed = removeOnBehalfActingReference(subscription);
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.UNSUBSCRIBE_FROM_SERVICE, tp
.getTriggerProcessParameters(), dataManager
.getCurrentUser().getOrganization()));
tp.addTriggerProcessParameter(TriggerProcessParameterName.SUBSCRIPTION,
buildNotification(oldSubscriptionId));
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.SUBSCRIPTION_TERMINATION, tp
.getTriggerProcessParameters(), subscription
.getProduct().getVendor()));
sendConfirmDeactivationEmail(removed, oldSubscriptionId, subscription);
}
void unsubscribe(Subscription subscription) {
// delete product
final Product product = subscription.getProduct();
product.setStatus(ServiceStatus.DELETED);
final Product asyncTempProduct = subscription.getAsyncTempProduct();
if (asyncTempProduct != null) {
subscription.setAsyncTempProduct(null);
dataManager.remove(asyncTempProduct);
}
modUpgBean.deleteModifiedEntityForSubscription(subscription);
// deactivate subscription
subscription.setStatus(SubscriptionStatus.DEACTIVATED);
long txTime = DateFactory.getInstance().getTransactionTime();
subscription.setDeactivationDate(Long.valueOf(txTime));
// log
audit.unsubscribeFromService(dataManager, subscription);
}
/**
* @param subscription
*/
private void stopInstance(Subscription subscription) {
boolean stopInstance = subscription.getStatus() != SubscriptionStatus.INVALID;
if (stopInstance) {
try {
appManager.deleteInstance(subscription);
} catch (SaaSApplicationException e) {
LOG.logError(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.ERROR_UNSUBSCRIBE_SUBSCRIPTION_FAILED,
Long.toString(subscription.getKey()));
manageBean.sendTechnicalServiceErrorMail(subscription);
}
}
}
private VONotification buildNotification(String subscriptionId) {
VONotificationBuilder builder = new VONotificationBuilder();
return builder.addParameter(VOProperty.SUBSCRIPTION_SUBSCRIPTION_ID,
subscriptionId).build();
}
private boolean removeOnBehalfActingReference(Subscription subscription) {
// execute isLastSubscription named query
Long isLastSubscription = getSubscriptionDao()
.hasSubscriptionsBasedOnOnBehalfServicesForTp(subscription);
// if is last subscription...
if (isLastSubscription.longValue() == 0) {
// search for the reference...
Organization sourceOrganization = subscription.getProduct()
.getTechnicalProduct().getOrganization();
Organization targetOrganization = subscription.getOrganization();
OrganizationReference reference = getOrganizationReference(
sourceOrganization, targetOrganization);
// if found remove it
if (reference != null) {
removeTemporaryOnbehalfUsers(sourceOrganization,
targetOrganization);
dataManager.remove(reference);
dataManager.flush();
return true;
}
}
return false;
}
private void removeTemporaryOnbehalfUsers(Organization sourceOrganization,
Organization targetOrganization) {
for (PlatformUser onbehalfUser : sourceOrganization
.getOnBehalfUsersFor(targetOrganization)) {
removeActiveSessionsForOnbehalfUser(onbehalfUser);
OnBehalfUserReference master = onbehalfUser.getMaster();
onbehalfUser.getOrganization().getPlatformUsers()
.remove(onbehalfUser);
dataManager.remove(master);
}
}
private void removeActiveSessionsForOnbehalfUser(PlatformUser onbehalfUser) {
List<Session> sessions = getSessionDao().getActiveSessionsForUser(
onbehalfUser);
for (Session s : sessions) {
dataManager.remove(s);
}
}
private void sendConfirmDeactivationEmail(boolean removed,
final String oldSubscriptionId, final Subscription subscription) {
EmailType emailType = removed ? EmailType.SUBSCRIPTION_DELETED_ON_BEHALF_ACTING
: EmailType.SUBSCRIPTION_DELETED;
Marketplace marketplace = subscription.getMarketplace();
List<PlatformUser> users = manageBean
.getCustomerAdminsAndSubscriptionOwner(subscription);
for (PlatformUser user : users) {
try {
commService.sendMail(user, emailType,
new Object[] { oldSubscriptionId }, marketplace);
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_DELETION_OF_SUBSCRIPTION_CONFIRMING_FAILED);
}
}
}
/**
* Obtains the subscription and verifies that the current settings allow a
* unsubscribe operation.
*
* @param subId
* The subscription id to unsubscribe from.
* @return The subscription to unsubscribe from.
* @throws SubscriptionStateException
* Thrown in case the operation cannot be performed due to the
* current state of the subscription.
* @throws SubscriptionStillActiveException
* Thrown in case the subscription is still active.
* @throws ObjectNotFoundException
* Thrown in case the subscription cannot be found.
*/
private Subscription validateSubsciptionForUnsubscribe(String subId)
throws SubscriptionStateException,
SubscriptionStillActiveException, ObjectNotFoundException {
Subscription subscription = manageBean.loadSubscription(subId, 0);
stateValidator.checkUnsubscribingAllowed(subscription);
// Check whether there are active sessions
List<Session> activeSessions = prodSessionMgmt
.getProductSessionsForSubscriptionTKey(subscription.getKey());
if (activeSessions.size() > 0) {
// there are still active sessions, so deletion must
// fail: throw exception
sessionCtx.setRollbackOnly();
SubscriptionStillActiveException ssa = new SubscriptionStillActiveException(
"There are still "
+ activeSessions.size()
+ " sessions active for the subscription with key '"
+ subscription.getKey() + "'",
SubscriptionStillActiveException.Reason.ACTIVE_SESSIONS);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, ssa,
LogMessageIdentifier.WARN_SUBSCRIPTION_DELETION_FAILED);
throw ssa;
}
return subscription;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public Subscription loadSubscription(long subscriptionKey)
throws ObjectNotFoundException {
return dataManager.getReference(Subscription.class, subscriptionKey);
}
/**
* Check if one of the platform parameter constraints are violated.
*
* @param subscription
* the subscription
* @param currentUser
* the current user
* @throws SubscriptionMigrationException
* in case one of the platform parameters is violated
*/
private void checkPlatformParameterConstraints(Subscription subscription,
Product targetProduct, PlatformUser currentUser)
throws SubscriptionMigrationException {
ParameterSet paramSet = targetProduct.getParameterSet();
if (paramSet == null || paramSet.getParameters() == null
|| paramSet.getParameters().isEmpty()) {
return;
}
for (Parameter param : paramSet.getParameters()) {
ParameterDefinition def = param.getParameterDefinition();
if (def.getParameterType() == ParameterType.PLATFORM_PARAMETER
&& param.getValue() != null) {
String subscriptionId = subscription.getSubscriptionId();
if (PlatformParameterIdentifiers.NAMED_USER.equals(def
.getParameterId())) {
int current = subscription.getUsageLicenses().size();
long max = param.getLongValue();
if (current > max) {
sessionCtx.setRollbackOnly();
SubscriptionMigrationException e = new SubscriptionMigrationException(
"Parameter check failed",
Reason.PARAMETER_USERS, new Object[] {
subscriptionId,
String.valueOf(current),
String.valueOf(max) });
LOG.logError(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.ERROR_MIGRATE_SUBSCRIPTION_AS_CHECK_PARAMETER,
Long.toString(currentUser.getKey()), Long
.toString(subscription.getKey()), Long
.toString(subscription
.getOrganizationKey()), def
.getParameterId());
throw e;
}
} else if (PlatformParameterIdentifiers.PERIOD.equals(def
.getParameterId())) {
long usedTime = DateFactory.getInstance()
.getTransactionTime()
- subscription.getActivationDate().longValue();
if (usedTime > param.getLongValue()) {
sessionCtx.setRollbackOnly();
SubscriptionMigrationException e = new SubscriptionMigrationException(
"Parameter check failed",
Reason.PARAMETER_PERIOD,
new Object[] { subscriptionId });
LOG.logError(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.ERROR_MIGRATE_SUBSCRIPTION_AS_CHECK_PARAMETER,
Long.toString(currentUser.getKey()), Long
.toString(subscription.getKey()), Long
.toString(subscription
.getOrganizationKey()), def
.getParameterId());
throw e;
}
}
}
}
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public List<VOService> getUpgradeOptions(String subscriptionId)
throws ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
Subscription subscription = manageBean.checkSubscriptionOwner(
subscriptionId, 0);
return getUpgradeOptions(subscription);
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public List<VOService> getUpgradeOptions(long subscriptionKey)
throws ObjectNotFoundException, OperationNotPermittedException {
Subscription subscription = manageBean.checkSubscriptionOwner(null,
subscriptionKey);
return getUpgradeOptions(subscription);
}
private List<VOService> getUpgradeOptions(Subscription subscription)
throws OperationNotPermittedException {
// 1. retrieve the related product
Organization organization = dataManager.getCurrentUser()
.getOrganization();
PermissionCheck.owns(subscription, organization, LOG);
Product product = subscription.getProduct();
// 2. retrieve and return the compatible products
List<Product> compatibleProducts = product.getCompatibleProductsList();
// 3. get customer specific products
long supplierKey = product.getVendor().getKey();
compatibleProducts = replaceByCustomerSpecificProducts(
compatibleProducts, supplierKey, organization);
List<VOService> result = new ArrayList<>(compatibleProducts.size());
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
for (Product prod : compatibleProducts) {
result.add(ProductAssembler.toVOProduct(prod, facade));
}
return result;
}
/**
* Replaces global products by customer specific products based on the
* global ones if existing. Global and specific products that are not active
* will be removed.
*
* @param products
* the products to get customer specific ones for
* @param supplierKey
* the supplier key identifying the owner of the products
* @param organization
* the customer organization to get customer specific products
* for
* @return the list containing the customer specific products and the global
* ones not having customer specific versions
*/
List<Product> replaceByCustomerSpecificProducts(List<Product> products,
long supplierKey, Organization organization) {
// read customer specific products
List<Product> customerProducts = getProductDao()
.getProductForCustomerOnly(supplierKey, organization);
// replace products by customer specific products if existent
Map<Long, Product> keyToProduct = new HashMap<>();
for (Product prod : customerProducts) {
keyToProduct.put(Long.valueOf(prod.getTemplate().getKey()), prod);
}
List<Product> temp = new ArrayList<>(products.size());
for (Product prod : products) {
Long key = Long.valueOf(prod.getKey());
if (keyToProduct.containsKey(key)) {
Product custSpec = keyToProduct.get(key);
if (custSpec.getStatus() == ServiceStatus.ACTIVE) {
temp.add(custSpec);
}
} else if (prod.getStatus() == ServiceStatus.ACTIVE) {
temp.add(prod);
}
}
return temp;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public VOSubscription upgradeSubscription(VOSubscription subscription,
VOService service, VOPaymentInfo paymentInfo,
VOBillingContact billingContact, List<VOUda> udas)
throws ObjectNotFoundException, OperationNotPermittedException,
SubscriptionMigrationException, PaymentInformationException,
SubscriptionStateException, ServiceChangedException,
PriceModelException, ConcurrentModificationException,
TechnicalServiceNotAliveException, OperationPendingException,
MandatoryUdaMissingException, NonUniqueBusinessKeyException,
ValidationException {
ArgumentValidator.notNull("subscription", subscription);
ArgumentValidator.notNull("service", service);
manageBean.checkSubscriptionOwner(subscription.getSubscriptionId(),
subscription.getKey());
validateSettingsForUpgrading(subscription, service, paymentInfo,
billingContact);
validateTriggerProcessForUpgradeSubscription(subscription);
TriggerProcess triggerProcess = createTriggerProcessForUpgradeSubscription(
subscription, service, paymentInfo, billingContact, udas);
TriggerDefinition triggerDefinition = triggerProcess
.getTriggerDefinition();
Subscription upgradedSub = null;
if (triggerDefinition == null) {
try {
upgradedSub = upgradeSubscriptionInt(triggerProcess);
} catch (ObjectNotFoundException | SubscriptionStateException
| OperationNotPermittedException | ServiceChangedException
| PriceModelException | PaymentInformationException
| SubscriptionMigrationException
| ConcurrentModificationException
| TechnicalServiceNotAliveException
| MandatoryUdaMissingException
| NonUniqueBusinessKeyException | ValidationException e) {
sessionCtx.setRollbackOnly();
throw e;
}
} else if (triggerDefinition.isSuspendProcess()) {
triggerProcess
.setTriggerProcessIdentifiers(TriggerProcessIdentifiers
.createUpgradeSubscription(dataManager,
TriggerType.UPGRADE_SUBSCRIPTION,
subscription));
dataManager.merge(triggerProcess);
}
return SubscriptionAssembler.toVOSubscription(upgradedSub,
new LocalizerFacade(localizer, dataManager.getCurrentUser()
.getLocale()));
}
private TriggerProcess createTriggerProcessForUpgradeSubscription(
VOSubscription subscription, VOService service,
VOPaymentInfo paymentInfo, VOBillingContact billingContact,
List<VOUda> udas) {
TriggerMessage message = new TriggerMessage(
TriggerType.UPGRADE_SUBSCRIPTION);
List<TriggerProcessMessageData> list = triggerQS
.sendSuspendingMessages(Collections.singletonList(message));
TriggerProcess triggerProcess = list.get(0).getTrigger();
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.OBJECT_ID,
subscription.getSubscriptionId());
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscription);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.PRODUCT, service);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.PAYMENTINFO, paymentInfo);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.BILLING_CONTACT, billingContact);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.UDAS, udas);
return triggerProcess;
}
private void validateTriggerProcessForUpgradeSubscription(
VOSubscription subscription) throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
if (validator.isModifyOrUpgradeSubscriptionPending(subscription)) {
String subID = subscription.getSubscriptionId();
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to upgrade or modify the subscription with ID '%s'",
subID), ReasonEnum.UPGRADE_SUBSCRIPTION,
new Object[] { subID });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_UPGRADE_SUBSCRIPTION_FAILED_DUE_TO_TRIGGER_CONFLICT,
subID);
throw ope;
}
}
private void validateTriggerProcessForUpgradeSubscriptionBySubscriptionKey(
long subscriptionKey, String subscriptionID)
throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
if (validator.isUpgradeSubscriptionPending(subscriptionKey)) {
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to upgrade or modify the subscription with ID '%s'",
subscriptionID), ReasonEnum.UPGRADE_SUBSCRIPTION,
new Object[] { subscriptionID });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_ADD_REVOKE_USER_FAILED_DUE_TO_TRIGGER_CONFLICT,
subscriptionID);
throw ope;
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public Subscription upgradeSubscriptionInt(TriggerProcess tp)
throws ObjectNotFoundException, SubscriptionStateException,
OperationNotPermittedException, ServiceChangedException,
PriceModelException, PaymentInformationException,
SubscriptionMigrationException, ConcurrentModificationException,
TechnicalServiceNotAliveException, NonUniqueBusinessKeyException,
ValidationException, MandatoryUdaMissingException {
VOSubscription current = tp.getParamValueForName(
TriggerProcessParameterName.SUBSCRIPTION).getValue(
VOSubscription.class);
VOService voTargetProduct = tp.getParamValueForName(
TriggerProcessParameterName.PRODUCT).getValue(VOService.class);
VOPaymentInfo voPaymentInfo = tp.getParamValueForName(
TriggerProcessParameterName.PAYMENTINFO).getValue(
VOPaymentInfo.class);
VOBillingContact voBillingContact = tp.getParamValueForName(
TriggerProcessParameterName.BILLING_CONTACT).getValue(
VOBillingContact.class);
List<VOUda> udas = ParameterizedTypes.list(
tp.getParamValueForName(TriggerProcessParameterName.UDAS)
.getValue(List.class), VOUda.class);
Product dbTargetProduct = dataManager.getReference(Product.class,
voTargetProduct.getKey());
Subscription dbSubscription = dataManager.getReference(
Subscription.class, current.getKey());
PlatformUser currentUser = dataManager.getCurrentUser();
Subscription subscription = manageBean.loadSubscription(
current.getSubscriptionId(), 0);
BaseAssembler.verifyVersionAndKey(subscription, current);
Product initialProduct = subscription.getProduct();
PaymentInfo initialPaymentInfo = subscription.getPaymentInfo();
BillingContact initialBillingContact = subscription.getBillingContact();
validateSettingsForUpgrading(current, voTargetProduct, voPaymentInfo,
voBillingContact);
// validates parameter version and parameter values
checkIfParametersAreModified(subscription, dbSubscription,
initialProduct, dbTargetProduct,
voTargetProduct.getParameters(), true);
PaymentInfo paymentInfo = null;
BillingContact bc = null;
if (voPaymentInfo != null) {
// Valid payment information have been passed -> use it for the
// upgraded subscription
paymentInfo = dataManager.getReference(PaymentInfo.class,
voPaymentInfo.getKey());
}
if (voBillingContact != null) {
bc = dataManager.getReference(BillingContact.class,
voBillingContact.getKey());
}
// log payment info before subscription changed!
audit.editPaymentType(dataManager, subscription, paymentInfo);
// log billing address before subscription changed!
audit.editBillingAddress(dataManager, subscription, bc);
// update subscription
subscription.setPaymentInfo(paymentInfo);
subscription.setBillingContact(bc);
// product and parameters are copied
copyProductAndModifyParametersForUpgrade(subscription, dbTargetProduct,
currentUser, voTargetProduct.getParameters());
List<Uda> existingUdas = manageBean.getExistingUdas(subscription);
List<VOUda> updatedList = getUpdatedSubscriptionAttributes(udas,
existingUdas);
logSubscriptionAttributeForEdit(subscription, updatedList);
if (dbTargetProduct.getTechnicalProduct().getProvisioningType()
.equals(ProvisioningType.SYNCHRONOUS)) {
// bugfix 8068
String oldServiceId = initialProduct.getTemplate() != null ? initialProduct
.getTemplate().getProductId() : initialProduct
.getProductId();
String newServiceId = dbTargetProduct.getTemplate() != null ? dbTargetProduct
.getTemplate().getProductId() : dbTargetProduct
.getProductId();
// remove old product
dataManager.remove(initialProduct);
saveUdasForSubscription(udas, subscription);
// finally send confirmation mail to the organization admin
modUpgBean.sendConfirmUpgradationEmail(subscription, oldServiceId,
newServiceId);
} else if (dbTargetProduct.getTechnicalProduct().getProvisioningType()
.equals(ProvisioningType.ASYNCHRONOUS)) {
long subscriptionKey = subscription.getKey();
if (paymentInfo != null) {
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_PAYMENTINFO,
String.valueOf(paymentInfo.getKey()));
}
if (bc != null) {
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_BILLINGCONTACT,
String.valueOf(bc.getKey()));
}
subscription.setPaymentInfo(initialPaymentInfo);
subscription.setBillingContact(initialBillingContact);
saveUdasForAsyncModifyOrUpgradeSubscription(udas, dbSubscription);
}
dataManager.flush();
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.UPGRADE_SUBSCRIPTION, tp
.getTriggerProcessParameters(), dataManager
.getCurrentUser().getOrganization()));
// log upDowngrade subscription
audit.upDowngradeSubscription(dataManager, subscription,
initialProduct, dbTargetProduct);
return subscription;
}
/**
* Validates the data of the specified subscription and target product to
* evaluate if the upgrade is possible.
*
* @param current
* The current subscription.
* @param newProduct
* The product to migrate to.
* @param voBillingContact
* @throws ObjectNotFoundException
* Thrown in case the subscription or target product cannot be
* found.
* @throws SubscriptionStateException
* Thrown in case the subscription state does not allow a
* migration.
* @throws OperationNotPermittedException
* Thrown in case the caller tries to modify another
* organization's object.
* @throws ServiceChangedException
* Thrown in case the target product definition has been
* modified in the meantime.
* @throws PriceModelException
* Thrown in case the target product is missing a price model.
* @throws PaymentInformationException
* Thrown in case the calling organization does not have a
* payment record.
* @throws SubscriptionMigrationException
* Thrown in case the migration is not possible as the products
* are not compatible.
*/
void validateSettingsForUpgrading(VOSubscription current,
VOService newProduct, VOPaymentInfo paymentInfo,
VOBillingContact voBillingContact) throws ObjectNotFoundException,
SubscriptionStateException, OperationNotPermittedException,
ServiceChangedException, PriceModelException,
PaymentInformationException, SubscriptionMigrationException {
// 1. retrieve the subscription details and the target product
Subscription subscription = manageBean.loadSubscription(
current.getSubscriptionId(), 0);
stateValidator.checkModifyAllowedForUpgrading(subscription);
PlatformUser currentUser = dataManager.getCurrentUser();
Organization organization = currentUser.getOrganization();
PermissionCheck.owns(subscription, organization, LOG);
Product currentProduct = subscription.getProduct();
Product targetProduct = dataManager.getReference(Product.class,
newProduct.getKey());
// check if the product has been changed in the meantime or it
// is inactive....
checkIfProductIsUptodate(targetProduct, newProduct);
// 2. check if the payment information parameter is set correctly
PriceModel targetPriceModel = targetProduct.getPriceModel();
if (targetPriceModel == null) {
PriceModelException mpme = new PriceModelException(
PriceModelException.Reason.NOT_DEFINED);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, mpme,
LogMessageIdentifier.WARN_MIGRATE_PRODUCT_FAILED,
Long.toString(targetProduct.getKey()));
throw mpme;
}
if (targetPriceModel.isChargeable()) {
PaymentDataValidator.validateNotNull(paymentInfo, voBillingContact);
PaymentInfo pi = dataManager.getReference(PaymentInfo.class,
paymentInfo.getKey());
BillingContact bc = dataManager.getReference(BillingContact.class,
voBillingContact.getKey());
PermissionCheck.owns(pi, organization, LOG);
PermissionCheck.owns(bc, organization, LOG);
PaymentDataValidator.validatePaymentTypeSupportedBySupplier(
organization, targetProduct, pi.getPaymentType());
PaymentDataValidator.validatePaymentInfoDataForUsage(pi);
}
// 3. now check if the new product is really compatible to the
// current one
List<Product> compatibleProducts = currentProduct
.getCompatibleProductsList();
// we won't find products in this list that are not active
compatibleProducts = replaceByCustomerSpecificProducts(
compatibleProducts, currentProduct.getVendorKey(), organization);
boolean isCompatibleProduct = false;
for (Product compatibleProduct : compatibleProducts) {
if (compatibleProduct.getKey() == targetProduct.getKey()) {
isCompatibleProduct = true;
}
}
if (!isCompatibleProduct) {
sessionCtx.setRollbackOnly();
SubscriptionMigrationException smf = new SubscriptionMigrationException(
"Migration of subscription failed",
Reason.INCOMPATIBLE_SERVICES, new Object[] {
subscription.getSubscriptionId(),
targetProduct.getCleanProductId() });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
smf,
LogMessageIdentifier.WARN_MIGRATE_PRODUCT_FAILED_NOT_COMPATIBLE,
Long.toString(currentUser.getKey()),
Long.toString(subscription.getKey()),
Long.toString(subscription.getOrganizationKey()),
Long.toString(targetProduct.getKey()),
Long.toString(subscription.getProduct().getKey()));
throw smf;
}
}
/**
* Copies the product and modifies the given parameters. Also informs the
* technical service about the changed parameter set.
*
* @param subscription
* the subscription to create a copy of the product for
* @param targetProduct
* the product to copy
* @param currentUser
* the currently logged in user
* @param voTargetParameters
* the list of modified or configurable parameters
* @throws SubscriptionMigrationException
* @throws TechnicalServiceNotAliveException
* Thrown in case the service for the operation cannot be
* reached.
*/
void copyProductAndModifyParametersForUpdate(Subscription subscription,
Product targetProduct, PlatformUser currentUser,
List<VOParameter> voTargetParameters)
throws SubscriptionMigrationException,
TechnicalServiceNotAliveException {
Product targetProductCopy = null;
ProvisioningType provisioningType = targetProduct.getTechnicalProduct()
.getProvisioningType();
if (provisioningType.equals(ProvisioningType.SYNCHRONOUS)) {
targetProductCopy = targetProduct;
} else if (provisioningType.equals(ProvisioningType.ASYNCHRONOUS)) {
targetProductCopy = copyProductForSubscription(targetProduct,
subscription, true);
}
List<Parameter> modifiedParametersForLog = updateConfiguredParameterValues(
targetProductCopy, voTargetParameters, subscription);
// verify the platform parameter and send the new parameter to the
// technical product
checkPlatformParameterConstraints(subscription, targetProductCopy,
currentUser);
try {
if (provisioningType.equals(ProvisioningType.ASYNCHRONOUS)) {
subscription.setAsyncTempProduct(targetProductCopy);
handleAsyncUpdateSubscription(subscription, targetProductCopy);
} else if (provisioningType.equals(ProvisioningType.SYNCHRONOUS)) {
// BUG 9998. It has to be ensured, that no call on pending
// subscription
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
appManager.modifySubscription(subscription);
}
}
} catch (TechnicalServiceNotAliveException e) {
sessionCtx.setRollbackOnly();
throw e;
} catch (TechnicalServiceOperationException e1) {
sessionCtx.setRollbackOnly();
Object[] params;
String subscriptionId = subscription.getSubscriptionId();
if (e1.getMessageParams() != null
&& e1.getMessageParams().length > 1) {
params = new Object[] { subscriptionId, e1.getMessage(),
e1.getMessageParams()[1] };
} else {
params = new Object[] { subscriptionId, e1.getMessage(), "" };
}
SubscriptionMigrationException smf = new SubscriptionMigrationException(
"Modify ParameterSet failed", Reason.PARAMETER, params);
LOG.logError(Log4jLogger.SYSTEM_LOG, smf,
LogMessageIdentifier.ERROR_MODIFY_PARAMETER_SET_FAILED);
throw smf;
}
audit.editSubscriptionParameterConfiguration(dataManager,
targetProductCopy, modifiedParametersForLog);
}
/**
* Copies the product and modifies the given parameters. Also informs the
* technical service about the changed parameter set.
*
* @param subscription
* the subscription to create a copy of the product for
* @param targetProduct
* the product to copy
* @param currentUser
* the currently logged in user
* @param voTargetParameters
* the list of modified or configurable parameters
* @throws SubscriptionMigrationException
* @throws TechnicalServiceNotAliveException
* Thrown in case the service for the operation cannot be
* reached.
* @throws ObjectNotFoundException
*/
void copyProductAndModifyParametersForUpgrade(Subscription subscription,
Product targetProduct, PlatformUser currentUser,
List<VOParameter> voTargetParameters)
throws SubscriptionMigrationException,
TechnicalServiceNotAliveException, ObjectNotFoundException {
ProvisioningType provisioningType = targetProduct.getTechnicalProduct()
.getProvisioningType();
Product targetProductCopy = copyProductForSubscription(targetProduct,
subscription, false);
List<Parameter> modifiedParametersForLog = updateConfiguredParameterValues(
targetProductCopy, voTargetParameters, subscription);
// verify the platform parameter
checkPlatformParameterConstraints(subscription, targetProductCopy,
currentUser);
try {
if (provisioningType.equals(ProvisioningType.ASYNCHRONOUS)) {
subscription.setAsyncTempProduct(targetProductCopy);
handleAsyncUpgradeSubscription(subscription, targetProductCopy);
} else if (provisioningType.equals(ProvisioningType.SYNCHRONOUS)) {
targetProductCopy.getPriceModel()
.setProvisioningCompleted(true);
subscription.bindToProduct(targetProductCopy);
// BE08022: Activate the subscription if it is up-/downgraded
if (isActivationAllowed(subscription, true)) {
appManager.activateInstance(subscription);
subscription.setStatus(SubscriptionStatus.ACTIVE);
}
// BUG 9998. It has to be ensured, that no call on pending
// subscription
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
appManager.upgradeSubscription(subscription);
}
}
} catch (TechnicalServiceNotAliveException e) {
sessionCtx.setRollbackOnly();
throw e;
} catch (TechnicalServiceOperationException e1) {
sessionCtx.setRollbackOnly();
Object[] params;
String subscriptionId = subscription.getSubscriptionId();
if (e1.getMessageParams() != null
&& e1.getMessageParams().length > 1) {
params = new Object[] { subscriptionId, e1.getMessage(),
e1.getMessageParams()[1] };
} else {
params = new Object[] { subscriptionId, e1.getMessage(), "" };
}
SubscriptionMigrationException smf = new SubscriptionMigrationException(
"Modify ParameterSet failed", Reason.PARAMETER, params);
LOG.logError(Log4jLogger.SYSTEM_LOG, smf,
LogMessageIdentifier.ERROR_MODIFY_PARAMETER_SET_FAILED);
throw smf;
}
audit.editSubscriptionParameterConfiguration(dataManager,
targetProductCopy, modifiedParametersForLog);
}
private Product copyProductForSubscription(Product targetProduct,
Subscription subscription, boolean provisiongCompleted) {
Product targetProductCopy = targetProduct.copyForSubscription(
targetProduct.getTargetCustomer(), subscription);
if (targetProductCopy.getPriceModel() != null) {
// FIXME LG clean
// For asynchronous upgrade the first target pricemodel version is
// created when subscription is still in PENDING_UPD, but must be
// fitered for billing. Set the indicating flag before persisting.
targetProductCopy.getPriceModel().setProvisioningCompleted(
provisiongCompleted);
}
try {
dataManager.persist(targetProductCopy);
} catch (NonUniqueBusinessKeyException ex) {
// this must never happen as the product copy must have unique
// id
SaaSSystemException se = new SaaSSystemException(
"The product copy method didn't create a unique productId.",
ex);
LOG.logError(
Log4jLogger.SYSTEM_LOG,
se,
LogMessageIdentifier.ERROR_CREATE_UNIQUE_PRODUCT_ID_FAILED_IN_PRODUCT_COPY);
throw se;
}
copyLocalizedPricemodelValues(targetProductCopy, targetProduct);
return targetProductCopy;
}
/**
* Sets subscription status and informs the technical service about the
* changed parameter set when asynchronously update subscription.
*
* @param subscription
* the subscription to update
* @param targetProduct
* the target product owned by the subscription
* @throws TechnicalServiceNotAliveException
* @throws TechnicalServiceOperationException
*/
void handleAsyncUpdateSubscription(Subscription subscription,
Product targetProduct) throws TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
EnumSet<SubscriptionStatus> set = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.SUSPENDED);
SubscriptionStatus status = subscription.getStatus();
if (set.contains(status)) {
appManager.asyncModifySubscription(subscription, targetProduct);
switch (status) {
case ACTIVE:
subscription.setStatus(SubscriptionStatus.PENDING_UPD);
break;
case SUSPENDED:
subscription.setStatus(SubscriptionStatus.SUSPENDED_UPD);
break;
default:
break;
}
}
}
/**
* Sets subscription status and informs the technical service about the
* changed parameter set when asynchronously upgrade subscription.
*
* @param subscription
* the subscription to update
* @param targetProduct
* the target product owned by the subscription
* @throws TechnicalServiceNotAliveException
* @throws TechnicalServiceOperationException
*/
void handleAsyncUpgradeSubscription(Subscription subscription,
Product targetProduct) throws TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
EnumSet<SubscriptionStatus> set = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.EXPIRED, SubscriptionStatus.SUSPENDED);
SubscriptionStatus status = subscription.getStatus();
if (set.contains(status)) {
appManager.asyncUpgradeSubscription(subscription, targetProduct);
switch (status) {
case ACTIVE:
subscription.setStatus(SubscriptionStatus.PENDING_UPD);
break;
case SUSPENDED:
subscription.setStatus(SubscriptionStatus.SUSPENDED_UPD);
break;
case EXPIRED:
default:
break;
}
}
}
boolean isActivationAllowed(Subscription subscription,
boolean activateExpiredSubscription) throws ObjectNotFoundException {
if (subscription == null) {
return false;
}
if (activateExpiredSubscription
&& (subscription.getStatus() == SubscriptionStatus.EXPIRED)) {
return true;
}
if (subscription.getStatus() != SubscriptionStatus.SUSPENDED) {
return false;
}
if (!subscription.getPriceModel().isChargeable()) {
return true;
}
if (subscription.getBillingContact() == null) {
return false;
}
PaymentType subPayType = null;
PaymentInfo paymentInfo = subscription.getPaymentInfo();
if (paymentInfo != null) {
subPayType = paymentInfo.getPaymentType();
}
if (subPayType == null) {
return false;
}
long serviceKey = subscription.getProduct().getKey();
boolean paymentEnabled;
paymentEnabled = accountService.isPaymentTypeEnabled(serviceKey,
subPayType.getKey());
return paymentEnabled;
}
/**
* Checks if the product read from the database is in active state and equal
* to the one passed in as voproduct comparing the versions.
*
* @param prod
* the product just read from the database
* @param voProd
* the product passed in through the interface
* @throws ServiceChangedException
* in case the product read from the database isn't active or
* version based different to the passed voproduct
*/
private void checkIfProductIsUptodate(Product prod, VOService voProd)
throws ServiceChangedException {
if (prod.getStatus() != ServiceStatus.ACTIVE) {
throw new ServiceChangedException(
ServiceChangedException.Reason.SERVICE_INACCESSIBLE);
}
if (prod.getVersion() != voProd.getVersion()) {
throw new ServiceChangedException(
ServiceChangedException.Reason.SERVICE_MODIFIED);
}
ParameterSet parameterSet = prod.getParameterSet();
if (parameterSet != null) {
List<Parameter> parameters = parameterSet.getParameters();
for (Parameter doParameter : parameters) {
for (VOParameter param : voProd.getParameters()) {
if (param.getKey() == doParameter.getKey()
&& param.getVersion() != doParameter.getVersion()) {
throw new ServiceChangedException(
ServiceChangedException.Reason.SERVICE_MODIFIED);
}
}
}
}
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public VOSubscriptionDetails modifySubscription(
VOSubscription subscription, List<VOParameter> parameters,
List<VOUda> udas) throws NonUniqueBusinessKeyException,
ObjectNotFoundException, OperationNotPermittedException,
ValidationException, SubscriptionMigrationException,
ConcurrentModificationException, TechnicalServiceNotAliveException,
OperationPendingException, MandatoryUdaMissingException,
SubscriptionStateException {
ArgumentValidator.notNull("subscription", subscription);
Subscription subFromDB = manageBean.checkSubscriptionOwner(
subscription.getSubscriptionId(), subscription.getKey());
validateSubscriptionSettings(subscription);
validateTriggerProcessForModifySubscription(subscription);
PlatformUser currentUser = dataManager.getCurrentUser();
boolean canModify = PermissionCheck
.shouldWeProceedWithUpdatingSubscription(subscription,
subFromDB, currentUser);
VOSubscriptionDetails result;
if (canModify) {
TriggerProcess triggerProcess = createTriggerProcessForModifySubscription(
subscription, parameters, udas);
result = processTriggerProcessForSubscriptionModification(
subscription, triggerProcess);
} else {
LocalizerFacade facade = new LocalizerFacade(localizer,
currentUser.getLocale());
result = SubscriptionAssembler.toVOSubscriptionDetails(subFromDB,
facade);
}
return result;
}
private VOSubscriptionDetails processTriggerProcessForSubscriptionModification(
VOSubscription subscription, TriggerProcess triggerProcess)
throws ObjectNotFoundException, NonUniqueBusinessKeyException,
ValidationException, OperationNotPermittedException,
SubscriptionMigrationException, ConcurrentModificationException,
TechnicalServiceNotAliveException, MandatoryUdaMissingException,
SubscriptionStateException {
VOSubscriptionDetails result = null;
TriggerDefinition triggerDefinition = triggerProcess
.getTriggerDefinition();
if (triggerDefinition == null) {
try {
result = modifySubscriptionInt(triggerProcess);
} catch (ObjectNotFoundException | NonUniqueBusinessKeyException
| OperationNotPermittedException
| SubscriptionMigrationException
| ConcurrentModificationException
| TechnicalServiceNotAliveException | ValidationException
| MandatoryUdaMissingException | SubscriptionStateException e) {
sessionCtx.setRollbackOnly();
throw e;
}
} else if (triggerDefinition.isSuspendProcess()) {
triggerProcess
.setTriggerProcessIdentifiers(TriggerProcessIdentifiers
.createUpgradeSubscription(dataManager,
TriggerType.MODIFY_SUBSCRIPTION,
subscription));
dataManager.merge(triggerProcess);
}
return result;
}
private TriggerProcess createTriggerProcessForModifySubscription(
VOSubscription subscription, List<VOParameter> parameters,
List<VOUda> udas) {
TriggerMessage message = new TriggerMessage(
TriggerType.MODIFY_SUBSCRIPTION);
List<TriggerProcessMessageData> list = triggerQS
.sendSuspendingMessages(Collections.singletonList(message));
TriggerProcess triggerProcess = list.get(0).getTrigger();
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.OBJECT_ID,
subscription.getSubscriptionId());
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscription);
List<VOParameter> params = parameters;
if (params == null) {
params = new ArrayList<>();
}
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.PARAMETERS, params);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.UDAS, udas);
return triggerProcess;
}
private void validateTriggerProcessForModifySubscription(
VOSubscription subscription) throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
String subID = subscription.getSubscriptionId();
if (validator.isModifyOrUpgradeSubscriptionPending(subscription)) {
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to modify or upgrade the subscription with key '%s'",
subID), ReasonEnum.MODIFY_SUBSCRIPTION,
new Object[] { subID });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_MODIFY_SUBSCRIPTION_FAILED_DUE_TO_TRIGGER_CONFLICT,
subID);
throw ope;
}
}
private void validateTriggerProcessForModifySubscriptionBySubscriptionKey(
long subscriptionKey, String subscriptionID)
throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
if (validator.isModifySubscriptionPending(subscriptionKey)) {
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to modify or upgrade the subscription with key '%s'",
subscriptionID), ReasonEnum.MODIFY_SUBSCRIPTION,
new Object[] { subscriptionID });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_ADD_REVOKE_USER_FAILED_DUE_TO_TRIGGER_CONFLICT,
subscriptionID);
throw ope;
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public VOSubscriptionDetails modifySubscriptionInt(TriggerProcess tp)
throws ObjectNotFoundException, NonUniqueBusinessKeyException,
ValidationException, OperationNotPermittedException,
SubscriptionMigrationException, ConcurrentModificationException,
TechnicalServiceNotAliveException, MandatoryUdaMissingException,
SubscriptionStateException {
VOSubscription subscription = tp.getParamValueForName(
TriggerProcessParameterName.SUBSCRIPTION).getValue(
VOSubscription.class);
List<VOParameter> modifiedParameters = ParameterizedTypes.list(tp
.getParamValueForName(TriggerProcessParameterName.PARAMETERS)
.getValue(List.class), VOParameter.class);
List<VOUda> udas = ParameterizedTypes.list(
tp.getParamValueForName(TriggerProcessParameterName.UDAS)
.getValue(List.class), VOUda.class);
Subscription dbSubscription = validateSubscriptionSettings(subscription);
final PlatformUser currentUser = dataManager.getCurrentUser();
Organization organization = currentUser.getOrganization();
UserGroup unit = getUnit(subscription.getUnitKey(),
subscription.getUnitName(), organization.getKey());
stateValidator.checkModifyAllowedForUpdating(dbSubscription);
// get initial values of subscription
String dbSubscriptionId = dbSubscription.getSubscriptionId();
boolean subIdChanged = !dbSubscriptionId.equals(subscription
.getSubscriptionId());
PlatformUser dbOwner = dbSubscription.getOwner();
Product dbProduct = dbSubscription.getProduct();
String dbPurchaseNumber = dbSubscription.getPurchaseOrderNumber();
UserGroup dbUnit = dbSubscription.getUserGroup();
// set new values for subscription
dbSubscription.setSubscriptionId(subscription.getSubscriptionId());
dbSubscription.setPurchaseOrderNumber(subscription
.getPurchaseOrderNumber());
if (currentUser.isOrganizationAdmin() || currentUser.isUnitAdmin()) {
dbSubscription.setUserGroup(unit);
}
manageBean.setSubscriptionOwner(dbSubscription,
subscription.getOwnerId(), true);
boolean backupOldValues = handleParameterModifications(
modifiedParameters, dbSubscription, currentUser, subIdChanged,
dbProduct);
List<Uda> existingUdas = manageBean.getExistingUdas(dbSubscription);
List<VOUda> updatedUdas = getUpdatedSubscriptionAttributes(udas,
existingUdas);
logSubscriptionAttributeForEdit(dbSubscription, updatedUdas);
logSubscriptionOwner(dbSubscription, dbOwner);
if (backupOldValues) {
long subscriptionKey = dbSubscription.getKey();
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_SUBSCRIPTIONID,
subscription.getSubscriptionId());
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_ORGANIZATIONID,
dbSubscription.getOrganization().getOrganizationId());
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_PURCHASEORDERNUMBER,
subscription.getPurchaseOrderNumber());
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_OWNERID,
subscription.getOwnerId());
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_UNIT,
String.valueOf(subscription.getUnitKey()));
// set initial values again
dbSubscription.setSubscriptionId(dbSubscriptionId);
dbSubscription.setPurchaseOrderNumber(dbPurchaseNumber);
String dbOwnerId = dbOwner == null ? null : dbOwner.getUserId();
manageBean.setSubscriptionOwner(dbSubscription, dbOwnerId, true);
dbSubscription.setUserGroup(dbUnit);
saveUdasForAsyncModifyOrUpgradeSubscription(udas, dbSubscription);
} else {
saveUdasForSubscription(udas, dbSubscription);
}
dataManager.flush();
LocalizerFacade facade = new LocalizerFacade(localizer,
currentUser.getLocale());
VOSubscriptionDetails result = SubscriptionAssembler
.toVOSubscriptionDetails(dbSubscription, facade);
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.MODIFY_SUBSCRIPTION, tp
.getTriggerProcessParameters(), dataManager
.getCurrentUser().getOrganization()));
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.SUBSCRIPTION_MODIFICATION, tp
.getTriggerProcessParameters(), dbSubscription
.getProduct().getVendor()));
return result;
}
private boolean handleParameterModifications(
List<VOParameter> modifiedParameters, Subscription dbSubscription,
final PlatformUser currentUser, boolean subIdChanged,
Product dbProduct) throws SubscriptionMigrationException,
ConcurrentModificationException, ValidationException,
TechnicalServiceNotAliveException {
try {
if (subIdChanged
|| checkIfParametersAreModified(dbSubscription,
dbSubscription, dbProduct, dbProduct,
modifiedParameters, false)) {
copyProductAndModifyParametersForUpdate(dbSubscription,
dbProduct, currentUser, modifiedParameters);
if (dbProduct.getTechnicalProduct().getProvisioningType()
.equals(ProvisioningType.ASYNCHRONOUS)) {
return true;
}
}
} catch (ServiceChangedException e) {
throw new ConcurrentModificationException(e.getMessage());
}
return false;
}
/**
* Validates the settings of the specified subscription object.
*
* @param subscription
* The subscription to be validated.
* @return The domain object representation of the subscription to be
* modified.
* @throws ValidationException
* Thrown in case the settings could not be validated.
* @throws ObjectNotFoundException
* Thrown in case the subscription could not be found.
* @throws OperationNotPermittedException
* Thrown in case the caller tries to modify another
* organization's object.
* @throws NonUniqueBusinessKeyException
* Thrown in case there already is a subscription with the given
* id for the current organization (only checked in caes of
* changing the current id).
* @throws ConcurrentModificationException
*/
private Subscription validateSubscriptionSettings(
VOSubscription subscription) throws ValidationException,
ObjectNotFoundException, OperationNotPermittedException,
NonUniqueBusinessKeyException, ConcurrentModificationException {
subscription.setSubscriptionId(BaseAssembler.trim(subscription
.getSubscriptionId()));
String subscriptionId = subscription.getSubscriptionId();
BLValidator.isId("subscriptionId", subscriptionId, true);
BLValidator.isDescription("purchaseOrderNumber",
subscription.getPurchaseOrderNumber(), false);
Subscription subscriptionToModify = dataManager.getReference(
Subscription.class, subscription.getKey());
PermissionCheck.owns(subscriptionToModify, dataManager.getCurrentUser()
.getOrganization(), LOG);
BaseAssembler.verifyVersionAndKey(subscriptionToModify, subscription);
String ownerId = subscription.getOwnerId();
if (ownerId != null && ownerId.length() != 0) {
checkRolesForSubscriptionOwner(ownerId);
}
if (!subscriptionToModify.getSubscriptionId().equals(subscriptionId)) {
Subscription sub = new Subscription();
sub.setOrganization(subscriptionToModify.getOrganization());
sub.setSubscriptionId(subscriptionId);
dataManager.validateBusinessKeyUniqueness(sub);
// Validate unique subscirptionId and organization in temporary
// table
Long result = getModifiedEntityDao()
.countSubscriptionOfOrganizationAndSubscription(
subscriptionToModify, subscriptionId);
if (result.longValue() > 0) {
NonUniqueBusinessKeyException ex = new NonUniqueBusinessKeyException();
LOG.logError(
Log4jLogger.SYSTEM_LOG,
ex,
LogMessageIdentifier.ERROR_SUBSCRIPTIONID_ALREADY_EXIST_IN_MODIFIEDENTITY,
subscriptionId, subscriptionToModify.getOrganization()
.getOrganizationId());
throw ex;
}
}
return subscriptionToModify;
}
void checkRolesForSubscriptionOwner(String ownerId)
throws ObjectNotFoundException, OperationNotPermittedException {
PlatformUser owner = idManager.getPlatformUser(ownerId, true);
if (!owner.hasSubscriptionOwnerRole()) {
String rolesString = UserRoleType.ORGANIZATION_ADMIN + ", "
+ UserRoleType.SUBSCRIPTION_MANAGER;
String message = "Add subscription owner failed. User '%s' does not have required roles: %s";
OperationNotPermittedException onp = new OperationNotPermittedException(
String.format(message, ownerId, rolesString));
LOG.logWarn(Log4jLogger.SYSTEM_LOG, onp,
LogMessageIdentifier.WARN_ADD_SUBSCRIPTION_OWNER_FAILED,
ownerId, rolesString);
throw onp;
}
}
/**
* To avoid unneeded migrations, check if parameters really have changed and
* if they can be changed
*
* @param dbSourceProduct
* the current product
* @param voTargetParameters
* the parameters to modify
* @return <code>true</code> if at least one parameter will be changed.
* @throws ConcurrentModificationException
* @throws ValidationException
*/
boolean checkIfParametersAreModified(Subscription subscription,
Subscription dbSubscription, Product dbSourceProduct,
Product dbTargetProduct, List<VOParameter> voTargetParameters,
boolean upgrade) throws SubscriptionMigrationException,
ServiceChangedException, ConcurrentModificationException,
ValidationException {
boolean result = false;
verifyIfParameterConcurrentlyChanged(dbTargetProduct,
voTargetParameters, upgrade);
// load db target product parameter and cache the values for better
// performance in a map
Map<String, Parameter> dbTargetParameterMap = new HashMap<>();
if (dbTargetProduct.getParameterSet() != null) {
for (Parameter dbTargetParameter : dbTargetProduct
.getParameterSet().getParameters()) {
dbTargetParameterMap.put(dbTargetParameter
.getParameterDefinition().getParameterId(),
dbTargetParameter);
}
}
Map<String, Parameter> dbSubscriptionParameterMap = new HashMap<>();
if (dbSubscription.getParameterSet() != null) {
for (Parameter dbSubParameter : dbSubscription.getParameterSet()
.getParameters()) {
dbSubscriptionParameterMap.put(dbSubParameter
.getParameterDefinition().getParameterId(),
dbSubParameter);
}
}
for (VOParameter voTargetParameter : voTargetParameters) {
String dbParameterId = voTargetParameter.getParameterDefinition()
.getParameterId();
if (dbSubscriptionParameterMap.containsKey(dbParameterId)) {
Parameter dbTargetParameter = dbTargetParameterMap
.get(dbParameterId);
Parameter dbSubscriptionParameter = dbSubscriptionParameterMap
.get(dbParameterId);
if (!upgrade
&& voTargetParameter.getParameterDefinition()
.getModificationType()
.equals(ParameterModificationType.ONE_TIME)) {
if (!compareParameterValue(dbTargetParameter,
dbSubscriptionParameter)) {
throw new ValidationException(
ValidationException.ReasonEnum.ONE_TIME_PARAMETER_NOT_ALLOWED,
null, new Object[] { dbTargetParameter
.getParameterDefinition()
.getParameterId() });
}
}
if (upgrade
&& !isParameterUpOrDowngradeValid(dbTargetParameter,
voTargetParameter)) {
String sourceProductId = dbSourceProduct
.getTemplateOrSelf().getProductId();
String targetProductId = dbTargetProduct
.getTemplateOrSelf().getProductId();
SubscriptionMigrationException e = new SubscriptionMigrationException(
"Incompatible parameter found",
Reason.INCOMPATIBLE_PARAMETER, new Object[] {
subscription.getSubscriptionId(),
sourceProductId,
targetProductId,
voTargetParameter.getParameterDefinition()
.getParameterId() });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
e,
LogMessageIdentifier.WARN_NOT_CONFIGURABLE_PARAMETER_OF_SUBSCRIPTION_MODIFIED,
dataManager.getCurrentUser().getUserId(),
dbParameterId,
Long.toString(dbSourceProduct.getKey()));
throw e;
}
if (dbTargetParameter.isValueSet()) {
// if currently no value is set, even null or empty as new
// value mean a change
if (!dbTargetParameter.getValue().equals(
voTargetParameter.getValue())) {
result = true;
}
} else {
// if no value is currently set, the new value only needs to
// be set if not null and not empty
if (voTargetParameter.getValue() != null
&& voTargetParameter.getValue().trim().length() > 0) {
result = true;
}
}
}
}
return result;
}
/**
* Verifies the version of a parameter.
*
* @param dbTargetProduct
* target product
* @param voTargetParameters
* VO target parameters
* @throws ConcurrentModificationException
* Is thrown if the parameter version changed or the parameter
* does not exist anymore.
*/
void verifyIfParameterConcurrentlyChanged(Product dbTargetProduct,
List<VOParameter> voTargetParameters, boolean upgrade)
throws ServiceChangedException, ConcurrentModificationException {
List<Parameter> dbTargetParameterList;
if (dbTargetProduct.getParameterSet() == null
|| dbTargetProduct.getParameterSet().getParameters() == null) {
dbTargetParameterList = new LinkedList<>();
} else {
dbTargetParameterList = dbTargetProduct.getParameterSet()
.getParameters();
}
if (upgrade
&& dbTargetParameterList.size() != voTargetParameters.size()) {
// Parameter changed, thus throw ex
throw new ServiceChangedException(
ServiceChangedException.Reason.SERVICE_MODIFIED);
}
Map<String, Parameter> dbParameterMap = new HashMap<>();
for (Parameter parameter : dbTargetParameterList) {
dbParameterMap.put(parameter.getParameterDefinition()
.getParameterId(), parameter);
}
for (VOParameter voParameter : voTargetParameters) {
Parameter dbParameter = dbParameterMap.get(voParameter
.getParameterDefinition().getParameterId());
if (dbParameter == null) {
String message = String.format(
"Parameter '%s' does not exist.", voParameter
.getParameterDefinition().getParameterId());
throw new ServiceChangedException(message);
}
BaseAssembler.verifyVersionAndKey(dbParameter, voParameter);
}
}
/**
* Matrix : <br/>
* 1. NOT CONFIGURABLE or CONFIGURABLE --> NOT CONFIGURABLE = OK, if values
* are identical or parameter modification type is one time<br/>
*
* 2. Otherwise true is returned
*
* @param dbParameter
* source (subscription) parameter
* @param targetParameter
* VO target parameter
* @return see matrix. False is also returned if the parameter id of the
* both parameters are not the same
*/
boolean isParameterUpOrDowngradeValid(Parameter dbParameter,
VOParameter targetParameter) {
if (!dbParameter
.getParameterDefinition()
.getParameterId()
.equals(targetParameter.getParameterDefinition()
.getParameterId())) {
return false;
}
if (dbParameter.getParameterDefinition().getModificationType() != targetParameter
.getParameterDefinition().getModificationType()) {
return false;
}
boolean targetOneTime = targetParameter.getParameterDefinition()
.getModificationType()
.equals(ParameterModificationType.ONE_TIME);
// non-configurable non-onetime parameter now only has default value,
// bug #9422
return !(!dbParameter.isConfigurable() && !targetOneTime)
|| compareParameterValue(dbParameter, targetParameter);
}
/**
* Compares the value of both parameters. A NULL value and empty String are
* treated identically.
*
* @param sourceParameter
* source (subscription) parameter
* @param targetParameter
* target parameter
* @return true, if identical, otherwise false
*/
private boolean compareParameterValue(Parameter sourceParameter,
Parameter targetParameter) {
String sourceParameterValue = sourceParameter.getValue() == null ? ""
: sourceParameter.getValue().trim();
String targetParameterValue = targetParameter.getValue() == null ? ""
: targetParameter.getValue().trim();
return sourceParameterValue.equals(targetParameterValue);
}
/**
* Compares the value of both parameters. A NULL value and empty String are
* treated identically.
*
* @param sourceParameter
* source (subscription) parameter
* @param targetParameter
* VO target parameter
* @return true, if identical, otherwise false
*/
private boolean compareParameterValue(Parameter sourceParameter,
VOParameter targetParameter) {
String sourceParameterValue = sourceParameter.getValue() == null ? ""
: sourceParameter.getValue().trim();
String targetParameterValue = targetParameter.getValue() == null ? ""
: targetParameter.getValue().trim();
return sourceParameterValue.equals(targetParameterValue);
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<String> getSubscriptionIdentifiers()
throws OrganizationAuthoritiesException {
Organization org = dataManager.getCurrentUser().getOrganization();
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING);
return getSubscriptionDao().getSubscriptionIdsForMyCustomers(org,
states);
}
private List<Subscription> getQueryResultListSubIdsAndOrgs(
Set<SubscriptionStatus> states) {
List<Subscription> result = new ArrayList<>();
result.addAll(executeQueryLoadSubIdsAndOrgsForMyCustomers(states));
Organization org = dataManager.getCurrentUser().getOrganization();
if (org.hasRole(OrganizationRoleType.SUPPLIER)) {
result.addAll(executeQueryLoadSubIdsAndOrgsForMyBrokerCustomers());
}
return result;
}
List<Subscription> getQueryResultListSubIdsAndOrgs(
Set<SubscriptionStatus> states, Pagination pagination) {
List<Subscription> result = new ArrayList<>();
Organization org = dataManager.getCurrentUser().getOrganization();
if (org.hasRole(OrganizationRoleType.SUPPLIER)) {
result.addAll(executeQueryLoadSubIdsAndOrgsForMyBrokerCustomers(
states, pagination));
} else {
result.addAll(executeQueryLoadSubIdsAndOrgsForMyCustomers(states,
pagination));
}
return result;
}
List<Subscription> executeQueryLoadSubIdsAndOrgsForMyCustomers(
Set<SubscriptionStatus> states) {
Organization org = dataManager.getCurrentUser().getOrganization();
return getSubscriptionDao().getSubscriptionsForMyCustomers(org, states);
}
List<Subscription> executeQueryLoadSubIdsAndOrgsForMyBrokerCustomers() {
Organization org = dataManager.getCurrentUser().getOrganization();
return getSubscriptionDao().getSubscriptionsForMyBrokerCustomers(org);
}
List<Subscription> executeQueryLoadSubIdsAndOrgsForMyCustomers(
Set<SubscriptionStatus> states, Pagination pagination) {
return getSubscriptionDao().getSubscriptionsForMyCustomers(
dataManager.getCurrentUser(), states, pagination);
}
List<Subscription> executeQueryLoadSubIdsAndOrgsForMyBrokerCustomers(
Set<SubscriptionStatus> states, Pagination pagination) {
return getSubscriptionDao().getSubscriptionsForMyBrokerCustomers(
dataManager.getCurrentUser(), states, pagination);
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<VOOrganization> getCustomersForSubscriptionId(
String subscriptionId) throws OrganizationAuthoritiesException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
List<VOOrganization> result = new ArrayList<>();
Organization offerer = dataManager.getCurrentUser().getOrganization();
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING);
List<Organization> customers = getOrganizationDao()
.getCustomersForSubscriptionId(offerer, subscriptionId, states);
LocalizerFacade lf = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
for (Organization customer : customers) {
result.add(OrganizationAssembler.toVOOrganization(customer, false,
lf, PerformanceHint.ONLY_IDENTIFYING_FIELDS));
}
return result;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public boolean expireOverdueSubscriptions(long currentTime) {
return terminateBean.expireOverdueSubscriptions(currentTime);
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public boolean expireSubscription(Subscription subscriptionToExpire) {
return terminateBean.expireSubscription(subscriptionToExpire);
}
/**
* Checks if the usercount of the subscription is lower or equal to the
* value of the product parameter NAMED_USER. If this condition does not
* hold, an ProductParameterException will be thrown.
*
* @param subscription
* The subscription to be checked.
* @throws ServiceParameterException
* Thrown in case the user count of the subscription is greater
* than the value of the product parameter NAMED_USER
*/
void verifyParameterNamedUser(Subscription subscription)
throws ServiceParameterException {
if (subscription == null) {
return;
}
ParameterSet parameterSet = subscription.getParameterSet();
if (parameterSet == null || parameterSet.getParameters() == null) {
return;
}
for (Parameter parameter : parameterSet.getParameters()) {
if (parameter.getParameterDefinition().getParameterType() == ParameterType.PLATFORM_PARAMETER
&& PlatformParameterIdentifiers.NAMED_USER.equals(parameter
.getParameterDefinition().getParameterId())) {
// if it is not defined to be mandatory, it can be empty
if (Strings.isEmpty(parameter.getValue())) {
return;
}
try {
// If a value is set, it must be ensured by validation that
// it is an integer - so the NumberFormatException should
// not happen
if (subscription.getActiveUsers().size() > Integer
.parseInt(parameter.getValue())) {
sessionCtx.setRollbackOnly();
String text = "Subscription '"
+ subscription.getSubscriptionId()
+ "'/Product '"
+ subscription.getProduct().getProductId()
+ "'";
ServiceParameterException e = new ServiceParameterException(
text, ParameterType.PLATFORM_PARAMETER,
PlatformParameterIdentifiers.NAMED_USER,
new Object[] { parameter.getValue(),
subscription.getSubscriptionId() });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_TOO_MANY_NAMED_USER_FOR_SUBSCRIPTION,
subscription.getSubscriptionId(), subscription
.getProduct().getProductId());
throw e;
}
} catch (NumberFormatException e) {
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_PROCESS_NAMED_USER_FAILED_AS_NUMBER_FORMAT,
parameter.getValue(), subscription.getProduct()
.getProductId());
}
}
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void informProductAboutNewUsers(Subscription sub,
List<PlatformUser> users) throws SubscriptionStateException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
stateValidator.checkInformProductAboutNewUsers(sub);
if (!canModifyApplicationUsers(sub)) {
return;
}
List<UsageLicense> licenses = getUsageLicensesForUsers(sub, users);
User[] createdUsers = appManager.createUsers(sub, licenses);
mapApplicationUserIdToLicense(licenses, createdUsers);
}
/**
* Maps the application user id back to the usage license and sets the
* affected usage license dirty
*
* @param licenses
* the usage licenses to update
* @param createdUsers
* the user array containing the application user id
*/
private void mapApplicationUserIdToLicense(List<UsageLicense> licenses,
User[] createdUsers) {
if (createdUsers == null) {
return;
}
String applicationUserId;
for (UsageLicense license : licenses) {
for (User createdUser : createdUsers) {
applicationUserId = createdUser.getApplicationUserId();
if (createdUser.getUserId().equals(
license.getUser().getUserId())
&& applicationUserId != null) {
license.setApplicationUserId(applicationUserId);
break;
}
}
}
}
/**
* Determines the usage license for the given users of the subscription.
*
* @param sub
* the subscription to get the usage licenses from
* @param users
* the users to get the usage licenses for
* @return the list of usage licenses
*/
private List<UsageLicense> getUsageLicensesForUsers(Subscription sub,
List<PlatformUser> users) {
List<UsageLicense> result = new ArrayList<>();
List<UsageLicense> licenses = sub.getUsageLicenses();
for (PlatformUser user : users) {
for (UsageLicense license : licenses) {
if (user.getKey() == license.getUser().getKey()) {
result.add(license);
}
}
}
return result;
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void abortAsyncSubscription(String subscriptionId,
String organizationId, List<VOLocalizedText> reason)
throws ObjectNotFoundException, SubscriptionStateException,
OrganizationAuthoritiesException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
manageBean.validateTechnoloyProvider(subscription);
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
throw new SubscriptionStateException(
"Operation not allowed for subscription "
+ subscription.getSubscriptionId(),
SubscriptionStateException.Reason.ONLY_PENDING);
}
abortSubscription(subscriptionId, subscription);
removeLocalizedResources(reason, subscription);
deleteProduct(subscription);
List<PlatformUser> receivers = loadReceiversForAbortAsyncSubscription(subscription);
sendSubscriptionAbortEmail(subscriptionId, organizationId,
subscription, receivers);
}
private void deleteProduct(Subscription subscription) {
Product product = subscription.getProduct();
product.setStatus(ServiceStatus.DELETED);
}
private void abortSubscription(String subscriptionId,
Subscription subscription) {
subscription.setStatus(SubscriptionStatus.INVALID);
subscription.setSubscriptionId(subscriptionId + "#"
+ String.valueOf(System.currentTimeMillis()));
}
void removeLocalizedResources(List<VOLocalizedText> reason,
Subscription subscription) {
long key = subscription.getKey();
localizer.removeLocalizedValues(key,
LocalizedObjectTypes.SUBSCRIPTION_PROVISIONING_PROGRESS);
localizer
.storeLocalizedResources(
key,
LocalizedObjectTypes.SUBSCRIPTION_PROVISIONING_PROGRESS,
reason);
}
void sendSubscriptionAbortEmail(String subscriptionId,
String organizationId, Subscription subscription,
List<PlatformUser> receivers) {
for (PlatformUser platformUser : receivers) {
LocalizerFacade facade = new LocalizerFacade(localizer,
platformUser.getLocale());
String text = facade.getText(subscription.getKey(),
LocalizedObjectTypes.SUBSCRIPTION_PROVISIONING_PROGRESS);
try {
commService.sendMail(platformUser,
EmailType.SUBSCRIPTION_INVALIDATED, new Object[] {
subscriptionId, organizationId, text },
subscription.getMarketplace());
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_INVALIDATION_SUBSCRIPTION_CONFIRMING_FAILED);
}
}
}
/**
* The mail for aborting asynchronous subscription is sent to:
*
* - administrators of the technology provider organization;<br/>
* - administrators of the customer organization;<br/>
* - subscription owner if it is not already administrator.
*/
List<PlatformUser> loadReceiversForAbortAsyncSubscription(
Subscription subscription) {
return manageBean
.getCustomerAndTechnicalProductAdminForSubscription(subscription);
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void completeAsyncSubscription(String subscriptionId,
String organizationId, VOInstanceInfo instanceInfo)
throws ObjectNotFoundException, SubscriptionStateException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException,
OrganizationAuthoritiesException, OperationNotPermittedException,
ValidationException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("instance", instanceInfo);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
String productInstanceId = instanceInfo.getInstanceId();
TechnicalProduct techProduct = subscription.getProduct()
.getTechnicalProduct();
if (getSubscriptionDao().checkIfProductInstanceIdExists(
productInstanceId, techProduct)) {
ValidationException ex = new ValidationException(
"The product instance ID already exist");
LOG.logError(
Log4jLogger.SYSTEM_LOG,
ex,
LogMessageIdentifier.ERROR_PRODUCT_INSTANCE_ID_ALREADY_EXIST);
throw ex;
}
updateInstanceInfoForCompletion(subscription, instanceInfo);
manageBean.validateTechnoloyProvider(subscription);
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
throw new SubscriptionStateException(
"Operation not allowed for subscription "
+ subscription.getSubscriptionId(),
SubscriptionStateException.Reason.ONLY_PENDING);
}
subscription.setActivationDate(Long.valueOf(DateFactory.getInstance()
.getTransactionTime()));
boolean deactivateInstance = !modUpgBean
.isPaymentValidOrFree(subscription);
if (deactivateInstance) {
subscription.setStatus(SubscriptionStatus.SUSPENDED);
} else {
activateSubscriptionFirstTime(subscription);
}
NotifyProvisioningServicePayload payload = new NotifyProvisioningServicePayload(
subscription.getKey(), deactivateInstance);
TaskMessage message = new TaskMessage(
NotifyProvisioningServiceHandler.class, payload);
tqs.sendAllMessages(Collections.singletonList(message));
PriceModel pm = subscription.getProduct().getPriceModel();
pm.setProvisioningCompleted(true);
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void updateAsyncSubscriptionProgress(String subscriptionId,
String organizationId, List<VOLocalizedText> progress)
throws ObjectNotFoundException, SubscriptionStateException,
OrganizationAuthoritiesException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
manageBean.validateTechnoloyProvider(subscription);
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
throw new SubscriptionStateException(
"Operation not allowed for subscription "
+ subscription.getSubscriptionId(),
SubscriptionStateException.Reason.ONLY_PENDING);
}
localizer.storeLocalizedResources(subscription.getKey(),
LocalizedObjectTypes.SUBSCRIPTION_PROVISIONING_PROGRESS,
progress);
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public boolean notifyAboutTimedoutSubscriptions(long currentTime) {
// we could also use a separate query inclusing the checked conditions
List<Subscription> subscriptions = getSubscriptionDao()
.getSubscriptionsByStatus(SubscriptionStatus.PENDING);
for (Subscription subscription : subscriptions) {
Long timeout = subscription.getProduct().getTechnicalProduct()
.getProvisioningTimeout();
if (!subscription.isTimeoutMailSent()
&& subscription.getCreationDate().longValue()
+ timeout.longValue() < currentTime) {
List<PlatformUser> users = subscription.getProduct()
.getTechnicalProduct().getOrganization()
.getPlatformUsers();
if (notifyTechnicalAdminsAboutTimeout(subscription, users)) {
// if at least one mail was sent, set the mail sent flag of
// the subscription
subscription.setTimeoutMailSent(true);
}
}
}
return true;
}
/**
* Tries to send a notification mail to the admin users contained in the
* list of users of the technical product owner organization informing about
* a timed out pending subscription.
*
* @param subscription
* the subscription that timed ot in pending state
* @param users
* the users of the organization owning the technical product
* @return <code>true</code> if at leas one mail was sent otherwise
* <code>false</code>
*/
private boolean notifyTechnicalAdminsAboutTimeout(
Subscription subscription, List<PlatformUser> users) {
boolean result = false;
String organizationId = subscription.getOrganization()
.getOrganizationId();
String subscriptionId = subscription.getSubscriptionId();
for (PlatformUser user : users) {
if (!user.isOrganizationAdmin()) {
continue;
}
try {
commService.sendMail(user, EmailType.SUBSCRIPTION_TIMEDOUT,
new Object[] { subscriptionId, organizationId },
subscription.getMarketplace());
// at least one admin could be informed
result = true;
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_TIMEOUT_OF_SUBSCRIPTION_NOTIFYING_FAILED);
}
}
return result;
}
/**
* Checks if the users of the subscription can be modified. this is not
* possible if the subscription is in pending or invalid state because no
* product instance is there in this case.
*
* @param subscription
* the subscription to modify the application side users for
* @return <code>true</code> if product instance can be informed otherwise
* <code>false</code>
*/
private boolean canModifyApplicationUsers(Subscription subscription) {
return !(subscription.getStatus() == SubscriptionStatus.PENDING || subscription
.getStatus() == SubscriptionStatus.INVALID);
}
/**
* It returns a list of VOSubscriptionIdAndOrganizations objects, which
* contain the subscriptionIdentifier and the associated customers of the
* subscription in form of list.If there are no subscriptions an empty list
* is returned.
*
* The role of organization as a supplier, a broker or a reseller is needed
* to execute this method.
*
* @return List<VOSubscriptionIdAndOrganizations>
*/
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<VOSubscriptionIdAndOrganizations> getCustomerSubscriptions()
throws OrganizationAuthoritiesException {
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING);
LocalizerFacade lf = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
List<Subscription> queryResultList = getQueryResultListSubIdsAndOrgs(states);
Map<String, VOSubscriptionIdAndOrganizations> mapSubIdsAndOrgs = getSubIdsAndOrgs(
lf, queryResultList);
return new ArrayList<VOSubscriptionIdAndOrganizations>(
mapSubIdsAndOrgs.values());
}
/**
* It returns a list of VOSubscriptionIdAndOrganizations objects, which
* contain the subscriptionIdentifier and the associated customers of the
* subscription in form of list.If there are no subscriptions an empty list
* is returned.
*
* The role of organization as a supplier, a broker or a reseller is needed
* to execute this method.
*
* @return List<VOSubscriptionIdAndOrganizations>
*/
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<VOSubscriptionIdAndOrganizations> getSubscriptionsForTerminate()
throws OrganizationAuthoritiesException {
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING, SubscriptionStatus.EXPIRED);
LocalizerFacade lf = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
List<Subscription> queryResultList = getQueryResultListSubIdsAndOrgs(states);
Map<String, VOSubscriptionIdAndOrganizations> mapSubIdsAndOrgs = getSubIdsAndOrgs(
lf, queryResultList);
return new ArrayList<VOSubscriptionIdAndOrganizations>(
mapSubIdsAndOrgs.values());
}
private Map<String, VOSubscriptionIdAndOrganizations> getSubIdsAndOrgs(
LocalizerFacade lf, List<Subscription> subscriptionList) {
Map<String, VOSubscriptionIdAndOrganizations> mapSubIdsAndOrgs = new LinkedHashMap<>();
for (Subscription subscription : subscriptionList) {
String subId = subscription.getSubscriptionId();
Organization customer = subscription.getOrganization();
if (mapSubIdsAndOrgs.containsKey(subId)) {
VOSubscriptionIdAndOrganizations subAndOrgs = mapSubIdsAndOrgs
.get(subId);
List<VOOrganization> customersForSubId = subAndOrgs
.getOrganizations();
customersForSubId.add(OrganizationAssembler.toVOOrganization(
customer, false, lf,
PerformanceHint.ONLY_IDENTIFYING_FIELDS));
subAndOrgs.setOrganizations(customersForSubId);
mapSubIdsAndOrgs.put(subId, subAndOrgs);
} else {
VOSubscriptionIdAndOrganizations subAndOrgs = new VOSubscriptionIdAndOrganizations();
subAndOrgs.setSubscriptionId(subId);
List<VOOrganization> customers = new ArrayList<>();
customers.add(OrganizationAssembler.toVOOrganization(customer,
false, lf, PerformanceHint.ONLY_IDENTIFYING_FIELDS));
subAndOrgs.setOrganizations(customers);
mapSubIdsAndOrgs.put(subId, subAndOrgs);
}
}
return mapSubIdsAndOrgs;
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public VOSubscriptionDetails getSubscriptionForCustomer(
String organizationId, String subscriptionId)
throws ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("subscriptionId", subscriptionId);
// find organization of customer
Organization customerTmpl = new Organization();
customerTmpl.setOrganizationId(organizationId);
Organization customer = (Organization) dataManager
.getReferenceByBusinessKey(customerTmpl);
final PlatformUser currentUser = dataManager.getCurrentUser();
PermissionCheck.sellerOfCustomer(currentUser.getOrganization(),
customer, LOG, sessionCtx);
Subscription subscriptionTmpl = new Subscription();
subscriptionTmpl.setSubscriptionId(subscriptionId);
subscriptionTmpl.setOrganizationKey(customer.getKey());
Subscription subscription = (Subscription) dataManager
.getReferenceByBusinessKey(subscriptionTmpl);
// fill subscription VO
LocalizerFacade facade = new LocalizerFacade(localizer,
currentUser.getLocale());
VOSubscriptionDetails voSubscriptionDetail = SubscriptionAssembler
.toVOSubscriptionDetails(subscription, facade);
// log view subscription
audit.viewSubscription(dataManager, subscription, customer);
return voSubscriptionDetail;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public List<VORoleDefinition> getServiceRolesForSubscription(
String subscriptionId) throws ObjectNotFoundException,
OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
Subscription sub = manageBean.checkSubscriptionOwner(subscriptionId, 0);
return getServiceRolesForSubscription(sub);
}
@Override
public List<VORoleDefinition> getServiceRolesForSubscription(
long subscriptionKey) throws ObjectNotFoundException,
OperationNotPermittedException {
Subscription sub = manageBean.checkSubscriptionOwner(null,
subscriptionKey);
return getServiceRolesForSubscription(sub);
}
private List<VORoleDefinition> getServiceRolesForSubscription(
Subscription subscription) {
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
List<RoleDefinition> roleDefinitions = subscription.getProduct()
.getTechnicalProduct().getRoleDefinitions();
return RoleAssembler.toVORoleDefinitions(roleDefinitions, facade);
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VORoleDefinition> getServiceRolesForService(VOService service)
throws ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("service", service);
Product prod = dataManager
.getReference(Product.class, service.getKey());
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
List<RoleDefinition> roleDefinitions = prod.getTechnicalProduct()
.getRoleDefinitions();
return RoleAssembler.toVORoleDefinitions(roleDefinitions, facade);
}
@Override
public void executeServiceOperation(VOSubscription subscription,
VOTechnicalServiceOperation operation)
throws ObjectNotFoundException, OperationNotPermittedException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException,
OrganizationAuthoritiesException, ConcurrentModificationException,
ValidationException, SubscriptionStateException,
NonUniqueBusinessKeyException {
ArgumentValidator.notNull("subscription", subscription);
ArgumentValidator.notNull("operation", operation);
Subscription sub = manageBean.loadSubscription(
subscription.getSubscriptionId(), 0);
stateValidator.checkExecuteServiceOperationAllowed(sub);
TechnicalProductOperation op = dataManager.getReference(
TechnicalProductOperation.class, operation.getKey());
BaseAssembler.verifyVersionAndKey(sub, subscription);
BaseAssembler.verifyVersionAndKey(op, operation);
List<VOServiceOperationParameter> list = operation
.getOperationParameters();
Map<String, String> params = new HashMap<>();
if (list != null) {
for (VOServiceOperationParameter p : list) {
params.put(p.getParameterId(), p.getParameterValue());
}
}
checkIfParamsModified(op, list);
String transactionid = IdGenerator.generateArtificialIdentifier();
OperationResult result = manageBean.executeServiceOperation(sub, op,
params, transactionid);
createOperationRecord(sub, op, transactionid, result.isAsyncExecution());
}
private void createOperationRecord(Subscription subscription,
TechnicalProductOperation operation, String transactionid,
boolean isAsyncExecution) throws NonUniqueBusinessKeyException {
Date executiondate = DateFactory.getInstance().getTransactionDate();
OperationRecord record = givenOperationRecord(subscription, operation,
executiondate, transactionid, isAsyncExecution);
operationRecordBean.createOperationRecord(record);
}
OperationRecord givenOperationRecord(Subscription subscription,
TechnicalProductOperation operation, Date executiondate,
String transactionid, boolean isAsyncExecution) {
OperationRecord record = new OperationRecord();
record.setTransactionid(transactionid);
record.setSubscription(subscription);
record.setTechnicalProductOperation(operation);
record.setExecutiondate(executiondate);
record.setUser(dataManager.getCurrentUser());
if (isAsyncExecution) {
record.setStatus(OperationStatus.RUNNING);
} else {
record.setStatus(OperationStatus.COMPLETED);
}
return record;
}
private void checkIfParamsModified(TechnicalProductOperation op,
List<VOServiceOperationParameter> list)
throws ConcurrentModificationException {
List<OperationParameter> opParams = op.getParameters();
Map<Long, OperationParameter> opParamsMap = new HashMap<>();
if (opParams != null) {
for (OperationParameter p : opParams) {
opParamsMap.put(Long.valueOf(p.getKey()), p);
}
}
if (opParamsMap.size() != list.size()) {
throw new ConcurrentModificationException();
}
for (VOServiceOperationParameter parameter : list) {
OperationParameter param = opParamsMap.get(Long.valueOf(parameter
.getKey()));
if (param == null) {
ConcurrentModificationException cme = new ConcurrentModificationException(
parameter);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, cme,
LogMessageIdentifier.WARN_CONCURRENT_MODIFICATION,
parameter.getClass().getSimpleName());
throw cme;
} else {
BaseAssembler.verifyVersionAndKey(param, parameter);
}
}
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "RESELLER_MANAGER" })
public void terminateSubscription(VOSubscription subscrVO, String reason)
throws ObjectNotFoundException, OrganizationAuthoritiesException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException,
ConcurrentModificationException, SubscriptionStateException {
ArgumentValidator.notNull("subscription", subscrVO);
Subscription subscription = loadSubscription(subscrVO.getKey());
BaseAssembler.verifyVersionAndKey(subscription, subscrVO);
// Remove corresponding operation record of the subscription
operationRecordBean.removeOperationsForSubscription(subscription
.getKey());
terminateBean.terminateSubscription(subscription, reason);
}
@Override
public boolean hasCurrentUserSubscriptions() {
String userKey = sessionCtx.getCallerPrincipal().getName();
Long userKeyLong;
try {
userKeyLong = Long.valueOf(userKey);
} catch (NumberFormatException e) {
SaaSSystemException saaSSystemException = new SaaSSystemException(e);
LOG.logError(Log4jLogger.SYSTEM_LOG, saaSSystemException,
LogMessageIdentifier.ERROR_WRONG_USER_KEY_IN_SESSION,
userKey);
throw saaSSystemException;
}
Long count = getSubscriptionDao().hasCurrentUserSubscriptions(
userKeyLong, VISIBLE_SUBSCRIPTION_STATUS);
return count.longValue() > 0;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public VOSubscriptionDetails modifySubscriptionPaymentData(
VOSubscription subscription, VOBillingContact billingContact,
VOPaymentInfo paymentInfo) throws ObjectNotFoundException,
ConcurrentModificationException, OperationNotPermittedException,
PaymentInformationException, SubscriptionStateException,
PaymentDataException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
ArgumentValidator.notNull("subscription", subscription);
Subscription sub = manageBean.checkSubscriptionOwner(
subscription.getSubscriptionId(), subscription.getKey());
PlatformUser user = dataManager.getCurrentUser();
Organization customer = user.getOrganization();
PermissionCheck.owns(sub, customer, LOG);
BaseAssembler.verifyVersionAndKey(sub, subscription);
EnumSet<SubscriptionStatus> set = EnumSet.of(
SubscriptionStatus.DEACTIVATED, SubscriptionStatus.EXPIRED,
SubscriptionStatus.INVALID);
if (set.contains(sub.getStatus())) {
Object[] params = new Object[] { sub.getStatus().name() };
SubscriptionStateException sse = new SubscriptionStateException(
SubscriptionStateException.Reason.SUBSCRIPTION_INVALID_STATE,
null, params);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, sse,
LogMessageIdentifier.WARN_SUBSCRIPTION_STATE_INVALID, sub
.getStatus().name());
throw sse;
}
if (!sub.getPriceModel().isChargeable()) {
if (billingContact != null || paymentInfo != null) {
PaymentDataException pde = new PaymentDataException(
"No payment info required for a non-chargeable price model",
PaymentDataException.Reason.NO_PAYMENT_REQUIRED);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, pde,
LogMessageIdentifier.WARN_NO_PAYMENT_INFO_REQUIRED);
throw pde;
}
}
PaymentInfo pi = null;
BillingContact bc = null;
if (sub.getPriceModel().isChargeable()) {
PaymentDataValidator.validateNotNull(paymentInfo, billingContact);
pi = dataManager.getReference(PaymentInfo.class,
paymentInfo.getKey());
bc = dataManager.getReference(BillingContact.class,
billingContact.getKey());
PermissionCheck.owns(pi, customer, LOG);
PermissionCheck.owns(bc, customer, LOG);
BaseAssembler.verifyVersionAndKey(pi, paymentInfo);
BaseAssembler.verifyVersionAndKey(bc, billingContact);
PaymentDataValidator.validatePaymentTypeSupportedBySupplier(
customer, sub.getProduct(), pi.getPaymentType());
PaymentDataValidator.validatePaymentInfoDataForUsage(pi);
SubscriptionStatus current = sub.getStatus();
if (current.isSuspendedOrSuspendedUpd()) {
try {
appManager.activateInstance(sub);
} catch (TechnicalServiceNotAliveException
| TechnicalServiceOperationException e) {
sessionCtx.setRollbackOnly();
throw e;
}
sub.setStatus(current.getNextForPaymentTypeRevoked());
}
}
// log before subscription changed!
audit.editPaymentType(dataManager, sub, pi);
audit.editBillingAddress(dataManager, sub, bc);
// change subscription
sub.setPaymentInfo(pi);
sub.setBillingContact(bc);
// flush to get the correct version of the subscription
dataManager.flush();
return SubscriptionAssembler.toVOSubscriptionDetails(sub,
new LocalizerFacade(localizer, user.getLocale()));
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public void reportIssue(String subscriptionId, String subject,
String issueText) throws IllegalArgumentException,
ObjectNotFoundException, OperationNotPermittedException,
MailOperationException, ValidationException {
manageBean.reportIssue(subscriptionId, subject, issueText);
}
void activateSubscriptionFirstTime(Subscription subscription) {
subscription.setStatus(SubscriptionStatus.ACTIVE);
Organization chargingOrganization = subscription.getProduct()
.determineChargingOrganization();
subscription.setCutOffDay(chargingOrganization.getCutOffDay());
}
/**
* Check if PaymentInfo or BillingContact is concurrently modified.
*
* @param paymentInfo
* the existing PaymentInfo stored in database
* @param billingContact
* the existing BillingContact stored in database
* @param voPaymentInfo
* @param voBillingContact
* @throws ConcurrentModificationException
*/
void validatePaymentInfoAndBillingContact(PaymentInfo paymentInfo,
BillingContact billingContact, VOPaymentInfo voPaymentInfo,
VOBillingContact voBillingContact)
throws ConcurrentModificationException {
BaseAssembler.verifyVersionAndKey(paymentInfo, voPaymentInfo);
BaseAssembler.verifyVersionAndKey(billingContact, voBillingContact);
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<Subscription> getSubscriptionsForManagers()
throws OrganizationAuthoritiesException {
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING, SubscriptionStatus.EXPIRED,
SubscriptionStatus.PENDING_UPD, SubscriptionStatus.SUSPENDED,
SubscriptionStatus.SUSPENDED_UPD);
return getQueryResultListSubIdsAndOrgs(states);
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<Subscription> getSubscriptionsForManagers(Pagination pagination)
throws OrganizationAuthoritiesException {
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING, SubscriptionStatus.EXPIRED,
SubscriptionStatus.PENDING_UPD, SubscriptionStatus.SUSPENDED,
SubscriptionStatus.SUSPENDED_UPD);
return getQueryResultListSubIdsAndOrgs(states, pagination);
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void completeAsyncModifySubscription(String subscriptionId,
String organizationId, VOInstanceInfo instance)
throws ObjectNotFoundException, SubscriptionStateException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException,
OrganizationAuthoritiesException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("instance", instance);
Subscription subscription = modUpgBean
.findSubscriptionForAsyncCallBack(subscriptionId,
organizationId);
stateValidator.checkCompleteModifyAllowed(subscription);
updateInstanceInfoForCompletion(subscription, instance);
manageBean.validateTechnoloyProvider(subscription);
modUpgBean.setStatusForModifyComplete(subscription);
Map<String, Parameter> paramMap = new HashMap<>();
if (subscription.getParameterSet() != null) {
for (Parameter parameter : subscription.getParameterSet()
.getParameters()) {
paramMap.put(parameter.getParameterDefinition()
.getParameterId(), parameter);
}
}
Product asyncTempProduct = subscription.getAsyncTempProduct();
if (asyncTempProduct.getParameterSet() != null) {
for (Parameter tempParam : asyncTempProduct.getParameterSet()
.getParameters()) {
String parameterID = tempParam.getParameterDefinition()
.getParameterId();
Parameter param = paramMap.get(parameterID);
if (param != null) {
param.setValue(tempParam.getValue());
}
}
}
subscription.setAsyncTempProduct(null);
dataManager.remove(asyncTempProduct);
modUpgBean.updateSubscriptionAttributesForAsyncUpdate(subscription);
List<PlatformUser> receivers = manageBean
.getCustomerAdminsAndSubscriptionOwner(subscription);
for (PlatformUser platformUser : receivers) {
try {
commService.sendMail(platformUser,
EmailType.SUBSCRIPTION_PARAMETER_MODIFIED,
new Object[] { subscriptionId },
subscription.getMarketplace());
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_MODIFY_PARAMETER_OF_SUBSCRIPTION_CONFIRMING_FAILED);
}
}
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void abortAsyncModifySubscription(String subscriptionId,
String organizationId, List<VOLocalizedText> reason)
throws ObjectNotFoundException, SubscriptionStateException,
OrganizationAuthoritiesException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
Subscription subscription = modUpgBean
.findSubscriptionForAsyncCallBack(subscriptionId,
organizationId);
stateValidator.checkAbortAllowedForModifying(subscription);
abortAsyncUpgradeOrModifySubscription(subscription, organizationId,
reason);
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void completeAsyncUpgradeSubscription(String subscriptionId,
String organizationId, VOInstanceInfo instance)
throws ObjectNotFoundException, TechnicalServiceOperationException,
OperationNotPermittedException, SubscriptionStateException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("instance", instance);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
stateValidator.checkCompleteUpgradeAllowed(subscription);
updateInstanceInfoForCompletion(subscription, instance);
manageBean.validateTechnoloyProvider(subscription);
Product initialProduct = subscription.getProduct();
Product asyncTempProduct = subscription.getAsyncTempProduct();
subscription.bindToProduct(asyncTempProduct);
subscription.setAsyncTempProduct(null);
modUpgBean.updateSubscriptionAttributesForAsyncUpgrade(subscription);
modUpgBean.setStatusForUpgradeComplete(subscription);
String oldServiceId = initialProduct.getTemplate() != null ? initialProduct
.getTemplate().getProductId() : initialProduct.getProductId();
String newServiceId = asyncTempProduct.getTemplate() != null ? asyncTempProduct
.getTemplate().getProductId() : asyncTempProduct.getProductId();
dataManager.remove(initialProduct);
dataManager.flush();
PriceModel pm = subscription.getProduct().getPriceModel();
pm.setProvisioningCompleted(true);
if (subscription.getStatus() == SubscriptionStatus.SUSPENDED) {
manageBean.suspend(subscription);
}
modUpgBean.sendConfirmUpgradationEmail(subscription, oldServiceId,
newServiceId, instance.getAccessInfo());
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void abortAsyncUpgradeSubscription(String subscriptionId,
String organizationId, List<VOLocalizedText> reason)
throws ObjectNotFoundException, SubscriptionStateException,
OrganizationAuthoritiesException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
stateValidator.checkAbortAllowedForUpgrading(subscription);
abortAsyncUpgradeOrModifySubscription(subscription, organizationId,
reason);
}
void abortAsyncUpgradeOrModifySubscription(Subscription subscription,
String organizationId, List<VOLocalizedText> reason)
throws OperationNotPermittedException {
manageBean.validateTechnoloyProvider(subscription);
final SubscriptionStatus currentState = subscription.getStatus();
subscription.setStatus(currentState.getNextForAbort());
Product asyncTempProduct = subscription.getAsyncTempProduct();
subscription.setAsyncTempProduct(null);
dataManager.remove(asyncTempProduct);
modUpgBean.deleteModifiedEntityForSubscription(subscription);
// send notify mail to administrators of the customer organization,
// subscription owner and technology provider organization
sendAbortAsyncModifySubscriptionEmail(subscription, organizationId,
reason);
}
void sendAbortAsyncModifySubscriptionEmail(Subscription subscription,
String organizationId, List<VOLocalizedText> reason) {
localizer.removeLocalizedValues(subscription.getKey(),
LocalizedObjectTypes.SUBSCRIPTION_MODIFICATION_REASON);
localizer.storeLocalizedResources(subscription.getKey(),
LocalizedObjectTypes.SUBSCRIPTION_MODIFICATION_REASON, reason);
dataManager.flush();
List<PlatformUser> receivers = manageBean
.getCustomerAndTechnicalProductAdminForSubscription(subscription);
for (PlatformUser platformUser : receivers) {
LocalizerFacade facade = new LocalizerFacade(localizer,
platformUser.getLocale());
String text = facade.getText(subscription.getKey(),
LocalizedObjectTypes.SUBSCRIPTION_MODIFICATION_REASON);
try {
commService.sendMail(platformUser,
EmailType.SUBSCRIPTION_PARAMETER_MODIFY_ABORT,
new Object[] { subscription.getSubscriptionId(),
organizationId, text },
subscription.getMarketplace());
} catch (MailOperationException e) {
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_MODIFY_PARAMETER_OF_SUBSCRIPTION_ABORT_CONFIRMING_FAILED);
}
}
}
@Override
public List<VOServiceOperationParameterValues> getServiceOperationParameterValues(
VOSubscription subscription, VOTechnicalServiceOperation operation)
throws ObjectNotFoundException, OperationNotPermittedException,
TechnicalServiceNotAliveException, ConcurrentModificationException,
TechnicalServiceOperationException {
ArgumentValidator.notNull("subscription", subscription);
ArgumentValidator.notNull("operation", operation);
Subscription sub = manageBean.loadSubscription(
subscription.getSubscriptionId(), 0);
TechnicalProductOperation op = dataManager.getReference(
TechnicalProductOperation.class, operation.getKey());
BaseAssembler.verifyVersionAndKey(sub, subscription);
BaseAssembler.verifyVersionAndKey(op, operation);
Map<String, List<String>> operationParameterValues = manageBean
.getOperationParameterValues(sub, op);
List<VOServiceOperationParameterValues> result = new LinkedList<>();
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
for (Entry<String, List<String>> e : operationParameterValues
.entrySet()) {
OperationParameter param = op.findParameter(e.getKey());
if (param != null) {
VOServiceOperationParameterValues vo = TechServiceOperationParameterAssembler
.toVOServiceOperationParameterValues(param, facade,
e.getValue());
result.add(vo);
}
}
return result;
}
void updateInstanceInfoForCompletion(Subscription subscription,
VOInstanceInfo info) throws TechnicalServiceOperationException {
new SubscriptionInstanceInfo(localizer, subscription)
.validateAndUpdateInstanceInfoForCompletion(info);
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void updateAccessInformation(String subscriptionId,
String organizationId, VOInstanceInfo instance)
throws ObjectNotFoundException, SubscriptionStateException,
OperationNotPermittedException, ValidationException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("instance", instance);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
manageBean.validateTechnoloyProvider(subscription);
checkIPAddressChangedAndSendMailToUsers(subscription, instance);
updateInstanceInfo(subscription, instance);
}
void checkIPAddressChangedAndSendMailToUsers(Subscription subscription,
VOInstanceInfo instance) {
String currentAccessInfo = instance.getAccessInfo();
String lastAccessInfo = null;
if (isUsableAWSAccessInfo(currentAccessInfo)) {
List<String> accessInfos = getSubscriptionHistoryDao()
.getAccessInfos(subscription, instance);
for (String oldAccessInfo : accessInfos) {
if (isUsableAWSAccessInfo(oldAccessInfo)) {
lastAccessInfo = oldAccessInfo;
break;
}
}
if (checkIPAddressChanged(lastAccessInfo, currentAccessInfo)) {
sendMailForIPAddressChanged(subscription, currentAccessInfo);
}
}
}
boolean checkIPAddressChanged(String lastAccessInfo,
String currentAccessInfo) {
return (lastAccessInfo != null && !lastAccessInfo.isEmpty() && !lastAccessInfo
.equals(currentAccessInfo));
}
private void sendMailForIPAddressChanged(Subscription subscription,
String currentAccessInfo) {
List<UsageLicense> userLicenses = getUsageLicenseDao()
.getUsersforSubscription(subscription);
EmailType emailType = EmailType.SUBSCRIPTION_ACCESSINFO_CHANGED;
Long marketplaceKey = null;
if (subscription.getMarketplace() != null) {
marketplaceKey = Long.valueOf(subscription.getMarketplace()
.getKey());
}
SendMailPayload payload = new SendMailPayload();
for (UsageLicense usageLicense : userLicenses) {
payload.addMailObjectForUser(usageLicense.getUser().getKey(),
emailType, new Object[] { subscription.getSubscriptionId(),
getPublicDNS(currentAccessInfo),
getIPAddress(currentAccessInfo),
getKeyPairName(currentAccessInfo) }, marketplaceKey);
}
TaskMessage message = new TaskMessage(SendMailHandler.class, payload);
tqs.sendAllMessages(Collections.singletonList(message));
}
boolean isAWSAccessInfo(String accessInfo) {
try {
String subAccessInfo = accessInfo.substring(
accessInfo.indexOf(":"), accessInfo.indexOf(KEY_PAIR_NAME));
return subAccessInfo.contains(AMAZONAWS_COM);
} catch (StringIndexOutOfBoundsException e) {
return false;
}
}
boolean isUsableAWSAccessInfo(String accessInfo) {
return !(accessInfo == null || accessInfo.isEmpty())
&& isAWSAccessInfo(accessInfo)
&& !hasNullAccessInfo(accessInfo);
}
boolean hasNullAccessInfo(String accessInfo) {
return getPublicDNS(accessInfo).isEmpty()
|| getIPAddress(accessInfo).isEmpty()
|| getKeyPairName(accessInfo).isEmpty();
}
String getPublicDNS(String accessInfo) {
try {
return accessInfo.substring(0, accessInfo.indexOf(KEY_PAIR_NAME));
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
String getIPAddress(String accessInfo) {
try {
return accessInfo
.substring(accessInfo.indexOf("-"), accessInfo.indexOf("."))
.substring(1).replace('-', '.');
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
String getKeyPairName(String accessInfo) {
try {
return accessInfo.substring(accessInfo.indexOf(KEY_PAIR_NAME),
accessInfo.length());
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
void updateInstanceInfo(Subscription subscription, VOInstanceInfo info)
throws ValidationException {
new SubscriptionInstanceInfo(localizer, subscription)
.validateAndUpdateInstanceInfo(info);
}
/**
* Save udas for asynchronously modify or upgrade subscription. Store uda
* value in modifieduda temporarily.
*
* @param udas
* The list of VOUda with new value.
* @param dbSubscription
* The subscription to be modified or upgraded.
*/
void saveUdasForAsyncModifyOrUpgradeSubscription(List<VOUda> udas,
Subscription dbSubscription) throws MandatoryUdaMissingException,
ValidationException, NonUniqueBusinessKeyException,
ObjectNotFoundException, OperationNotPermittedException,
ConcurrentModificationException {
Organization supplier = dbSubscription.getProduct()
.getSupplierOrResellerTemplate().getVendor();
manageBean.getUdaAccess().validateUdaAndAdaptTargetKey(udas, supplier,
dbSubscription);
List<VOUda> newUdas = new ArrayList<>();
List<VOUda> defaultValueUdas = new ArrayList<>();
for (VOUda voUda : udas) {
if (voUda.getKey() > 0) {
modUpgBean.storeModifiedUda(voUda.getKey(),
ModifiedEntityType.UDA_VALUE, voUda.getUdaValue(),
dbSubscription.getKey());
} else {
newUdas.add(voUda);
}
}
for (VOUda voUda : newUdas) {
VOUda defaultValueUda = new VOUda();
defaultValueUda.setTargetObjectKey(voUda.getTargetObjectKey());
defaultValueUda.setUdaDefinition(voUda.getUdaDefinition());
defaultValueUda.setUdaValue(voUda.getUdaDefinition()
.getDefaultValue());
defaultValueUdas.add(defaultValueUda);
}
manageBean.getUdaAccess().saveUdas(defaultValueUdas,
dbSubscription.getOrganization());
for (VOUda voUda : newUdas) {
Uda uda = new Uda();
uda.setTargetObjectKey(voUda.getTargetObjectKey());
uda.setUdaDefinitionKey(voUda.getUdaDefinition().getKey());
uda = (Uda) dataManager.getReferenceByBusinessKey(uda);
modUpgBean.storeModifiedUda(uda.getKey(),
ModifiedEntityType.UDA_VALUE, voUda.getUdaValue(),
dbSubscription.getKey());
}
}
public SubscriptionHistoryDao getSubscriptionHistoryDao() {
return new SubscriptionHistoryDao(dataManager);
}
public UsageLicenseDao getUsageLicenseDao() {
return new UsageLicenseDao(dataManager);
}
public SubscriptionDao getSubscriptionDao() {
return new SubscriptionDao(dataManager);
}
public MarketplaceDao getMarketplaceDao() {
return new MarketplaceDao(dataManager);
}
public ModifiedEntityDao getModifiedEntityDao() {
return new ModifiedEntityDao(dataManager);
}
public OrganizationDao getOrganizationDao() {
return new OrganizationDao(dataManager);
}
public ProductDao getProductDao() {
return new ProductDao(dataManager);
}
public SessionDao getSessionDao() {
return new SessionDao(dataManager);
}
@Override
@RolesAllowed({ "TECHNOLOGY_MANAGER" })
public void updateAsyncOperationProgress(String transactionId,
OperationStatus status, List<VOLocalizedText> progress)
throws OperationNotPermittedException, OperationStateException {
ArgumentValidator.notNull("transactionId", transactionId);
ArgumentValidator.notNull("status", status);
operationRecordBean.updateOperationStatus(transactionId, status,
progress);
}
@Override
@RolesAllowed({ "TECHNOLOGY_MANAGER" })
public void updateAsyncSubscriptionStatus(String subscriptionId,
String organizationId, VOInstanceInfo instanceInfo)
throws ObjectNotFoundException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("instance", instanceInfo);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
subscription.setStatus(SubscriptionStatus.PENDING);
List<PlatformUser> receivers = manageBean
.getCustomerAdminsAndSubscriptionOwner(subscription);
for (PlatformUser platformUser : receivers) {
try {
commService.sendMail(
platformUser,
EmailType.SUBSCRIPTION_INSTANCE_NOT_FOUND,
new Object[] { subscriptionId,
instanceInfo.getInstanceId() },
subscription.getMarketplace());
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_MODIFY_PARAMETER_OF_SUBSCRIPTION_CONFIRMING_FAILED);
}
}
}
@TransactionAttribute(TransactionAttributeType.MANDATORY)
private List<Subscription> getSubscriptionsForUserInt(PlatformUser user,
Pagination pagination) {
return getSubscriptionDao().getSubscriptionsForUser(user, pagination);
}
@Override
public List<Subscription> getSubscriptionsForCurrentUser(
Pagination pagination) {
PlatformUser user = dataManager.getCurrentUser();
return getSubscriptionsForUserInt(user, pagination);
}
@Override
public UsageLicense getSubscriptionUsageLicense(PlatformUser user,
Long subKey) {
return getSubscriptionDao().getUserLicense(user,
subKey == null ? -1 : subKey.longValue());
}
@Override
public void removeSubscriptionOwner(Subscription sub) {
sub.setOwner(null);
dataManager.merge(sub);
}
@Override
public Subscription getMySubscriptionDetails(long key) {
return getSubscriptionDao().getMySubscriptionDetails(key);
}
}
| oscm-subscriptionmgmt/javasrc/org/oscm/subscriptionservice/bean/SubscriptionServiceBean.java | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2015
*
* Creation Date: 2009-02-05
*
*******************************************************************************/
package org.oscm.subscriptionservice.bean;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.interceptor.Interceptors;
import org.oscm.accountservice.assembler.OrganizationAssembler;
import org.oscm.accountservice.assembler.UdaAssembler;
import org.oscm.accountservice.dataaccess.UdaAccess;
import org.oscm.accountservice.local.AccountServiceLocal;
import org.oscm.applicationservice.local.ApplicationServiceLocal;
import org.oscm.communicationservice.local.CommunicationServiceLocal;
import org.oscm.configurationservice.local.ConfigurationServiceLocal;
import org.oscm.converter.ParameterizedTypes;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.BillingContact;
import org.oscm.domobjects.CatalogEntry;
import org.oscm.domobjects.Marketplace;
import org.oscm.domobjects.OnBehalfUserReference;
import org.oscm.domobjects.OperationParameter;
import org.oscm.domobjects.OperationRecord;
import org.oscm.domobjects.Organization;
import org.oscm.domobjects.OrganizationRefToPaymentType;
import org.oscm.domobjects.OrganizationReference;
import org.oscm.domobjects.OrganizationRole;
import org.oscm.domobjects.OrganizationToRole;
import org.oscm.domobjects.Parameter;
import org.oscm.domobjects.ParameterDefinition;
import org.oscm.domobjects.ParameterSet;
import org.oscm.domobjects.PaymentInfo;
import org.oscm.domobjects.PaymentType;
import org.oscm.domobjects.PlatformUser;
import org.oscm.domobjects.PriceModel;
import org.oscm.domobjects.Product;
import org.oscm.domobjects.RoleDefinition;
import org.oscm.domobjects.Session;
import org.oscm.domobjects.Subscription;
import org.oscm.domobjects.TechnicalProduct;
import org.oscm.domobjects.TechnicalProductOperation;
import org.oscm.domobjects.TriggerDefinition;
import org.oscm.domobjects.TriggerProcess;
import org.oscm.domobjects.TriggerProcessIdentifier;
import org.oscm.domobjects.TriggerProcessParameter;
import org.oscm.domobjects.Uda;
import org.oscm.domobjects.UsageLicense;
import org.oscm.domobjects.UserGroup;
import org.oscm.domobjects.enums.LocalizedObjectTypes;
import org.oscm.domobjects.enums.ModifiedEntityType;
import org.oscm.domobjects.enums.OrganizationReferenceType;
import org.oscm.i18nservice.bean.LocalizerFacade;
import org.oscm.i18nservice.local.LocalizerServiceLocal;
import org.oscm.id.IdGenerator;
import org.oscm.identityservice.assembler.UserDataAssembler;
import org.oscm.identityservice.local.IdentityServiceLocal;
import org.oscm.interceptor.AuditLogDataInterceptor;
import org.oscm.interceptor.DateFactory;
import org.oscm.interceptor.ExceptionMapper;
import org.oscm.interceptor.InvocationDateContainer;
import org.oscm.internal.intf.SubscriptionService;
import org.oscm.internal.tables.Pagination;
import org.oscm.internal.types.enumtypes.ConfigurationKey;
import org.oscm.internal.types.enumtypes.OperationStatus;
import org.oscm.internal.types.enumtypes.OrganizationRoleType;
import org.oscm.internal.types.enumtypes.ParameterModificationType;
import org.oscm.internal.types.enumtypes.ParameterType;
import org.oscm.internal.types.enumtypes.PerformanceHint;
import org.oscm.internal.types.enumtypes.ServiceAccessType;
import org.oscm.internal.types.enumtypes.ServiceStatus;
import org.oscm.internal.types.enumtypes.ServiceType;
import org.oscm.internal.types.enumtypes.SubscriptionStatus;
import org.oscm.internal.types.enumtypes.TriggerType;
import org.oscm.internal.types.enumtypes.UserRoleType;
import org.oscm.internal.types.exception.ConcurrentModificationException;
import org.oscm.internal.types.exception.DomainObjectException;
import org.oscm.internal.types.exception.IllegalArgumentException;
import org.oscm.internal.types.exception.MailOperationException;
import org.oscm.internal.types.exception.MandatoryUdaMissingException;
import org.oscm.internal.types.exception.NonUniqueBusinessKeyException;
import org.oscm.internal.types.exception.ObjectNotFoundException;
import org.oscm.internal.types.exception.OperationNotPermittedException;
import org.oscm.internal.types.exception.OperationPendingException;
import org.oscm.internal.types.exception.OperationPendingException.ReasonEnum;
import org.oscm.internal.types.exception.OperationStateException;
import org.oscm.internal.types.exception.OrganizationAuthoritiesException;
import org.oscm.internal.types.exception.PaymentDataException;
import org.oscm.internal.types.exception.PaymentInformationException;
import org.oscm.internal.types.exception.PriceModelException;
import org.oscm.internal.types.exception.SaaSApplicationException;
import org.oscm.internal.types.exception.SaaSSystemException;
import org.oscm.internal.types.exception.ServiceChangedException;
import org.oscm.internal.types.exception.ServiceParameterException;
import org.oscm.internal.types.exception.SubscriptionAlreadyExistsException;
import org.oscm.internal.types.exception.SubscriptionMigrationException;
import org.oscm.internal.types.exception.SubscriptionMigrationException.Reason;
import org.oscm.internal.types.exception.SubscriptionStateException;
import org.oscm.internal.types.exception.SubscriptionStillActiveException;
import org.oscm.internal.types.exception.TechnicalServiceNotAliveException;
import org.oscm.internal.types.exception.TechnicalServiceOperationException;
import org.oscm.internal.types.exception.ValidationException;
import org.oscm.internal.vo.VOBillingContact;
import org.oscm.internal.vo.VOInstanceInfo;
import org.oscm.internal.vo.VOLocalizedText;
import org.oscm.internal.vo.VOOrganization;
import org.oscm.internal.vo.VOParameter;
import org.oscm.internal.vo.VOPaymentInfo;
import org.oscm.internal.vo.VORoleDefinition;
import org.oscm.internal.vo.VOService;
import org.oscm.internal.vo.VOServiceOperationParameter;
import org.oscm.internal.vo.VOServiceOperationParameterValues;
import org.oscm.internal.vo.VOSubscription;
import org.oscm.internal.vo.VOSubscriptionDetails;
import org.oscm.internal.vo.VOSubscriptionIdAndOrganizations;
import org.oscm.internal.vo.VOTechnicalServiceOperation;
import org.oscm.internal.vo.VOUda;
import org.oscm.internal.vo.VOUsageLicense;
import org.oscm.internal.vo.VOUser;
import org.oscm.internal.vo.VOUserSubscription;
import org.oscm.logging.Log4jLogger;
import org.oscm.logging.LoggerFactory;
import org.oscm.notification.vo.VONotification;
import org.oscm.notification.vo.VOProperty;
import org.oscm.operation.data.OperationResult;
import org.oscm.permission.PermissionCheck;
import org.oscm.provisioning.data.User;
import org.oscm.serviceprovisioningservice.assembler.ProductAssembler;
import org.oscm.serviceprovisioningservice.assembler.RoleAssembler;
import org.oscm.serviceprovisioningservice.assembler.TechServiceOperationParameterAssembler;
import org.oscm.sessionservice.local.SessionServiceLocal;
import org.oscm.string.Strings;
import org.oscm.subscriptionservice.assembler.SubscriptionAssembler;
import org.oscm.subscriptionservice.auditlog.SubscriptionAuditLogCollector;
import org.oscm.subscriptionservice.dao.MarketplaceDao;
import org.oscm.subscriptionservice.dao.ModifiedEntityDao;
import org.oscm.subscriptionservice.dao.OrganizationDao;
import org.oscm.subscriptionservice.dao.ProductDao;
import org.oscm.subscriptionservice.dao.SessionDao;
import org.oscm.subscriptionservice.dao.SubscriptionDao;
import org.oscm.subscriptionservice.dao.SubscriptionHistoryDao;
import org.oscm.subscriptionservice.dao.UsageLicenseDao;
import org.oscm.subscriptionservice.local.SubscriptionListServiceLocal;
import org.oscm.subscriptionservice.local.SubscriptionServiceLocal;
import org.oscm.taskhandling.local.TaskMessage;
import org.oscm.taskhandling.local.TaskQueueServiceLocal;
import org.oscm.taskhandling.operations.NotifyProvisioningServiceHandler;
import org.oscm.taskhandling.operations.SendMailHandler;
import org.oscm.taskhandling.payloads.NotifyProvisioningServicePayload;
import org.oscm.taskhandling.payloads.SendMailPayload;
import org.oscm.techproductoperation.bean.OperationRecordServiceLocalBean;
import org.oscm.tenantprovisioningservice.bean.TenantProvisioningServiceBean;
import org.oscm.tenantprovisioningservice.vo.TenantProvisioningResult;
import org.oscm.triggerservice.bean.TriggerProcessIdentifiers;
import org.oscm.triggerservice.local.TriggerMessage;
import org.oscm.triggerservice.local.TriggerProcessMessageData;
import org.oscm.triggerservice.local.TriggerQueueServiceLocal;
import org.oscm.triggerservice.notification.VONotificationBuilder;
import org.oscm.triggerservice.validator.TriggerProcessValidator;
import org.oscm.types.constants.Configuration;
import org.oscm.types.enumtypes.EmailType;
import org.oscm.types.enumtypes.LogMessageIdentifier;
import org.oscm.types.enumtypes.PlatformParameterIdentifiers;
import org.oscm.types.enumtypes.ProvisioningType;
import org.oscm.types.enumtypes.TriggerProcessIdentifierName;
import org.oscm.types.enumtypes.TriggerProcessParameterName;
import org.oscm.types.enumtypes.UdaTargetType;
import org.oscm.types.exceptions.UserAlreadyAssignedException;
import org.oscm.types.exceptions.UserNotAssignedException;
import org.oscm.usergroupservice.bean.UserGroupServiceLocalBean;
import org.oscm.validation.ArgumentValidator;
import org.oscm.validation.PaymentDataValidator;
import org.oscm.validator.ADMValidator;
import org.oscm.validator.BLValidator;
import org.oscm.vo.BaseAssembler;
/**
* Session Bean implementation class of SubscriptionService (Remote IF) and
* SubscriptionServiceLocal (Local IF)
*/
@Stateless
@Remote(SubscriptionService.class)
@Local(SubscriptionServiceLocal.class)
@Interceptors({ InvocationDateContainer.class, ExceptionMapper.class,
AuditLogDataInterceptor.class })
public class SubscriptionServiceBean implements SubscriptionService,
SubscriptionServiceLocal {
public static final String KEY_PAIR_NAME = "Key pair name";
public static final String AMAZONAWS_COM = "amazonaws.com";
private static final Log4jLogger LOG = LoggerFactory
.getLogger(SubscriptionServiceBean.class);
@EJB(beanInterface = ApplicationServiceLocal.class)
protected ApplicationServiceLocal appManager;
@EJB(beanInterface = SessionServiceLocal.class)
protected SessionServiceLocal prodSessionMgmt;
@EJB
protected DataService dataManager;
@EJB
protected IdentityServiceLocal idManager;
@EJB
protected TenantProvisioningServiceBean tenantProvisioning;
@EJB
protected CommunicationServiceLocal commService;
@EJB(beanInterface = LocalizerServiceLocal.class)
protected LocalizerServiceLocal localizer;
@EJB(beanInterface = ConfigurationServiceLocal.class)
ConfigurationServiceLocal cfgService;
@EJB(beanInterface = SubscriptionListServiceLocal.class)
SubscriptionListServiceLocal subscriptionListService;
@EJB(beanInterface = TriggerQueueServiceLocal.class)
protected TriggerQueueServiceLocal triggerQS;
@EJB(beanInterface = TaskQueueServiceLocal.class)
public TaskQueueServiceLocal tqs;
@EJB(beanInterface = AccountServiceLocal.class)
public AccountServiceLocal accountService;
@EJB
SubscriptionAuditLogCollector audit;
@Resource
protected SessionContext sessionCtx;
@Inject
public TerminateSubscriptionBean terminateBean;
@Inject
public ManageSubscriptionBean manageBean;
@Inject
public ValidateSubscriptionStateBean stateValidator;
@Inject
public ModifyAndUpgradeSubscriptionBean modUpgBean;
@Inject
public OperationRecordServiceLocalBean operationRecordBean;
@Inject
UserGroupServiceLocalBean userGroupService;
private static final List<SubscriptionStatus> VISIBLE_SUBSCRIPTION_STATUS = Arrays
.asList(SubscriptionStatus.ACTIVE, SubscriptionStatus.EXPIRED,
SubscriptionStatus.PENDING, SubscriptionStatus.PENDING_UPD,
SubscriptionStatus.SUSPENDED,
SubscriptionStatus.SUSPENDED_UPD);
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public VOSubscription subscribeToService(VOSubscription subscription,
VOService service, List<VOUsageLicense> users,
VOPaymentInfo paymentInfo, VOBillingContact billingContact,
List<VOUda> udas) throws ObjectNotFoundException,
NonUniqueBusinessKeyException, ValidationException,
PaymentInformationException, ServiceParameterException,
ServiceChangedException, PriceModelException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationNotPermittedException,
SubscriptionAlreadyExistsException, OperationPendingException,
MandatoryUdaMissingException, ConcurrentModificationException,
SubscriptionStateException {
ArgumentValidator.notNull("subscription", subscription);
ArgumentValidator.notNull("service", service);
Subscription sub;
PlatformUser currentUser = dataManager.getCurrentUser();
checkIfServiceAvailable(service.getKey(), service.getServiceId(),
currentUser);
checkIfSubscriptionAlreadyExists(service);
verifyIdAndKeyUniqueness(currentUser, subscription);
validateSettingsForSubscribing(subscription, service, paymentInfo,
billingContact);
validateUserAssignmentForSubscribing(service, users);
validateTriggerProcessForCreateSubscription(subscription);
TriggerProcess triggerProcess = createTriggerProcessForCreateSubscription(
subscription, service, users, paymentInfo, billingContact, udas);
VOSubscription voSub = null;
TriggerDefinition triggerDefinition = triggerProcess
.getTriggerDefinition();
if (triggerDefinition == null) {
try {
sub = subscribeToServiceInt(triggerProcess);
voSub = SubscriptionAssembler.toVOSubscription(sub,
new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale()));
autoAssignUser(service, sub);
} catch (ObjectNotFoundException | ValidationException
| ServiceChangedException | PriceModelException
| PaymentInformationException
| NonUniqueBusinessKeyException
| TechnicalServiceNotAliveException
| TechnicalServiceOperationException
| ServiceParameterException
| ConcurrentModificationException
| MandatoryUdaMissingException | SubscriptionStateException e) {
sessionCtx.setRollbackOnly();
throw e;
}
} else if (triggerDefinition.isSuspendProcess()) {
triggerProcess
.setTriggerProcessIdentifiers(TriggerProcessIdentifiers
.createUnsubscribeFromService(dataManager,
TriggerType.SUBSCRIBE_TO_SERVICE,
subscription.getSubscriptionId()));
dataManager.merge(triggerProcess);
}
return voSub;
}
private void autoAssignUser(VOService service, Subscription sub)
throws ObjectNotFoundException, ServiceParameterException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationNotPermittedException,
ConcurrentModificationException {
Product prod = dataManager
.getReference(Product.class, service.getKey());
TechnicalProduct techProd = prod.getTechnicalProduct();
if (ProvisioningType.SYNCHRONOUS.equals(techProd.getProvisioningType())
&& service.isAutoAssignUserEnabled().booleanValue()) {
assignUsersForSubscription(sub.getSubscriptionId(), service);
}
}
void assignUsersForSubscription(String subscriptionId, VOService service)
throws ObjectNotFoundException, ServiceParameterException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationNotPermittedException,
ConcurrentModificationException {
PlatformUser currentUser = dataManager.getCurrentUser();
assignUsersForSubscription(subscriptionId, service, currentUser);
}
void assignUsersForSubscription(String subscriptionId, VOService service,
PlatformUser userToAssign) throws ObjectNotFoundException,
OperationNotPermittedException, ServiceParameterException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, ConcurrentModificationException {
List<VORoleDefinition> serviceRoles = getServiceRolesForService(service);
// If the service roles are defined for technical service,
// assign the first role to user to avoid assignment failure.
// If service roles are not defined, set default role to null.
List<VOUsageLicense> usersToBeAdded = new ArrayList<>();
VOUsageLicense lic = new VOUsageLicense();
lic.setUser(UserDataAssembler.toVOUserDetails(userToAssign));
lic.setRoleDefinition((serviceRoles == null || serviceRoles.isEmpty()) ? null
: serviceRoles.get(0));
usersToBeAdded.add(lic);
TriggerProcess proc = new TriggerProcess();
proc.addTriggerProcessParameter(TriggerProcessParameterName.OBJECT_ID,
subscriptionId);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscriptionId);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.USERS_TO_ADD, usersToBeAdded);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.USERS_TO_REVOKE, null);
addRevokeUserInt(proc);
}
/**
* @param subscription
* @return
* @throws OperationPendingException
*/
private void validateTriggerProcessForCreateSubscription(
VOSubscription subscription) throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
String subscriptionId = subscription.getSubscriptionId();
if (validator.isSubscribeOrUnsubscribeServicePending(subscriptionId)) {
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to create a subscription or unsubscribe from the subscription with identifier '%s'",
subscriptionId), ReasonEnum.SUBSCRIBE_TO_SERVICE,
new Object[] { subscriptionId });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_SUBSCRIBE_TO_SERVICE_FAILED_DUE_TO_TRIGGER_CONFLICT,
subscriptionId);
throw ope;
}
}
private TriggerProcess createTriggerProcessForCreateSubscription(
VOSubscription subscription, VOService service,
List<VOUsageLicense> users, VOPaymentInfo paymentInfo,
VOBillingContact billingContact, List<VOUda> udas) {
TriggerMessage message = new TriggerMessage(
TriggerType.SUBSCRIBE_TO_SERVICE);
List<TriggerProcessMessageData> list = triggerQS
.sendSuspendingMessages(Collections.singletonList(message));
TriggerProcess triggerProcess = list.get(0).getTrigger();
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.OBJECT_ID,
subscription.getSubscriptionId());
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscription);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.PRODUCT, service);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.USERS, users);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.PAYMENTINFO, paymentInfo);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.BILLING_CONTACT, billingContact);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.UDAS, udas);
return triggerProcess;
}
void saveUdasForSubscription(List<VOUda> udas, Subscription subscription)
throws ObjectNotFoundException, NonUniqueBusinessKeyException,
ValidationException, OperationNotPermittedException,
ConcurrentModificationException, MandatoryUdaMissingException {
Organization supplier = subscription.getProduct()
.getSupplierOrResellerTemplate().getVendor();
UdaAccess udaAccess = new UdaAccess(dataManager, sessionCtx);
udaAccess.saveUdasForSubscription(udas, supplier, subscription);
}
/**
* Checks if the technical product the marketing service belongs to has
* service roles defined and if the roles defined for the user assignments
* are part of this set and defined.
*
* @param product
* the product to subscribe to
* @param users
* the users to assign
* @throws ObjectNotFoundException
* if the product or a role wasn't found
* @throws OperationNotPermittedException
* if the role to assign doesn't belong to the products
* technical product or if no role is set when using service
* roles.
*/
private void validateUserAssignmentForSubscribing(VOService product,
List<VOUsageLicense> users) throws ObjectNotFoundException,
OperationNotPermittedException {
Product prod = dataManager
.getReference(Product.class, product.getKey());
if (users == null) {
return;
}
for (VOUsageLicense lic : users) {
getAndCheckServiceRole(lic, prod);
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public Subscription subscribeToServiceInt(TriggerProcess tp)
throws ObjectNotFoundException, ValidationException,
OperationNotPermittedException, ServiceChangedException,
PriceModelException, PaymentInformationException,
NonUniqueBusinessKeyException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, ServiceParameterException,
SubscriptionAlreadyExistsException,
ConcurrentModificationException, MandatoryUdaMissingException,
SubscriptionStateException {
PlatformUser currentUser = dataManager.getCurrentUser();
Organization organization = currentUser.getOrganization();
// read parameters from trigger process
VOSubscription subscription = tp.getParamValueForName(
TriggerProcessParameterName.SUBSCRIPTION).getValue(
VOSubscription.class);
VOService product = tp.getParamValueForName(
TriggerProcessParameterName.PRODUCT).getValue(VOService.class);
VOPaymentInfo voPaymentInfo = tp.getParamValueForName(
TriggerProcessParameterName.PAYMENTINFO).getValue(
VOPaymentInfo.class);
VOBillingContact voBillingContact = tp.getParamValueForName(
TriggerProcessParameterName.BILLING_CONTACT).getValue(
VOBillingContact.class);
List<?> udas = tp
.getParamValueForName(TriggerProcessParameterName.UDAS)
.getValue(List.class);
PlatformUser owner = dataManager.getReference(PlatformUser.class, tp
.getUser().getKey());
checkIfSubscriptionAlreadyExists(product);
UserGroup unit = getUnit(subscription.getUnitKey(),
subscription.getUnitName(), organization.getKey());
validateSettingsForSubscribing(subscription, product, voPaymentInfo,
voBillingContact);
Product productTemplate = dataManager.getReference(Product.class,
product.getKey());
Organization vendor = productTemplate.getVendor();
Organization supplier = dataManager
.getReference(Product.class, product.getKey())
.getSupplierOrResellerTemplate().getVendor();
List<VOUda> originalCustomerUdas = getUdasForCustomer("CUSTOMER",
dataManager.getCurrentUser().getOrganization().getKey(),
supplier);
OrganizationReference refVendorCust = null;
if (!organization.getVendorsOfCustomer().contains(vendor)) {
refVendorCust = new OrganizationReference(vendor, organization,
OrganizationReferenceType
.getOrgRefTypeForSourceRoles(vendor
.getGrantedRoleTypes()));
dataManager.persist(refVendorCust);
}
if (vendor.getGrantedRoleTypes().contains(OrganizationRoleType.BROKER)
&& !organization.getVendorsOfCustomer().contains(
productTemplate.getTemplate().getVendor())) {
refVendorCust = new OrganizationReference(productTemplate
.getTemplate().getVendor(), organization,
OrganizationReferenceType.SUPPLIER_TO_CUSTOMER);
dataManager.persist(refVendorCust);
}
if (refVendorCust != null) {
enableDefaultPaymentsForCustomer(refVendorCust);
}
// Look for the marketplace where the service is published
Marketplace mp = null;
Product publishedService = productTemplate.getType() == ServiceType.CUSTOMER_TEMPLATE ? productTemplate
.getTemplate() : productTemplate;
List<Marketplace> mps = getMarketplaceDao().getMarketplaceByService(
publishedService);
for (Marketplace m : mps) {
mp = m; // current assumption is that there's only one marketplace
break;
}
// Create a new subscription object
Subscription newSub = new Subscription();
Long creationTime = Long.valueOf(DateFactory.getInstance()
.getTransactionTime());
newSub.setCreationDate(creationTime);
newSub.setStatus(SubscriptionStatus.PENDING);
// set default cut-off day (db unique constrain)
newSub.setCutOffDay(1);
newSub.setSubscriptionId(subscription.getSubscriptionId().trim());
newSub.setPurchaseOrderNumber(subscription.getPurchaseOrderNumber());
newSub.setOrganization(organization);
// for subscribing service, set the current user as subscription owner
newSub.setOwner(owner);
verifyUnitAndRoles(currentUser, unit, newSub);
Product theProduct = productTemplate.copyForSubscription(
productTemplate.getTargetCustomer(), newSub);
if (theProduct.getPriceModel() != null) {
// FIXME LG clean
// The first target pricemodel version is created when subscription
// is still in PENDING, but must be fitered for billing. Set the
// indicating flag before persisting.
theProduct.getPriceModel().setProvisioningCompleted(false);
}
// to avoid id conflicts in high load scenarios add customer
// organization hash
theProduct.setProductId(theProduct.getProductId()
+ organization.hashCode());
theProduct.setOwningSubscription(null);
// subscription copies do not have/need a CatalogEntry
theProduct.setCatalogEntries(new ArrayList<CatalogEntry>());
theProduct.getPriceModel().setUuid(productTemplate.getPriceModel().getUuid());
try {
dataManager.persist(theProduct);
} catch (NonUniqueBusinessKeyException e) {
SaaSSystemException sse = new SaaSSystemException(
"The product copy for product '"
+ product.getKey()
+ "' cannot be stored, as the business key already exists.",
e);
LOG.logError(
Log4jLogger.SYSTEM_LOG,
sse,
LogMessageIdentifier.ERROR_CREATE_CUSTOMER_FOR_SPECIFIC_PRICEMODEL_FAILED,
Long.toString(dataManager.getCurrentUser().getKey()));
throw sse;
}
copyLocalizedPricemodelValues(theProduct, productTemplate);
// update the subscription's configurable parameter
List<Parameter> modifiedParametersForLog = updateConfiguredParameterValues(
theProduct, product.getParameters(), null);
// now bind the product and the price model to the subscription:
newSub.bindToProduct(theProduct);
// register the marketplace the subscription was coming from
newSub.setMarketplace(mp);
// Link the passed payment information to this subscription
if (voPaymentInfo != null) {
PaymentInfo paymentInfo = dataManager.getReference(
PaymentInfo.class, voPaymentInfo.getKey());
newSub.setPaymentInfo(paymentInfo);
}
if (voBillingContact != null) {
BillingContact bc = dataManager.getReference(BillingContact.class,
voBillingContact.getKey());
newSub.setBillingContact(bc);
}
// persist the subscription. This is essential to ensure the
// subscription exists and also eliminates all potential problems
// with a subsequent call to the application.
dataManager.persist(newSub);
theProduct.setOwningSubscription(newSub);
createAllowOnBehalfActingReference(newSub);
TenantProvisioningResult provisioningResult = createInstanceAndAddUsersToSubscription(
tp, newSub);
newSub.setSuccessMessage(provisioningResult.getResultMesage());
dataManager.flush();
saveUdasForSubscription(ParameterizedTypes.list(udas, VOUda.class),
newSub);
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.SUBSCRIPTION_CREATION,
tp.getTriggerProcessParameters(), vendor));
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.SUBSCRIBE_TO_SERVICE, tp
.getTriggerProcessParameters(), dataManager
.getCurrentUser().getOrganization()));
sendSubscriptionCreatedMailToAdministrators(newSub, newSub.getProduct()
.getTechnicalProduct().isAllowingOnBehalfActing());
// Used for Autoassign a service which was supended via trigger
// (subscribeToService)
autoAssignUserForTriggerProcess(tp, product, owner, newSub);
audit.editSubscriptionParameterConfiguration(dataManager, theProduct,
modifiedParametersForLog);
audit.subscribeToService(dataManager, newSub);
logSubscriptionAttributeForCreation(newSub,
ParameterizedTypes.list(udas, VOUda.class),
originalCustomerUdas);
return newSub;
}
private void verifyUnitAndRoles(PlatformUser currentUser, UserGroup unit, Subscription newSub) throws OperationNotPermittedException {
if(!currentUser.isOrganizationAdmin()){
boolean isUnitAdmin = currentUser.isUnitAdmin();
boolean isSubMgr = currentUser.isSubscriptionManager();
boolean isUnitToBeAssigned = unit != null;
boolean unitIsMandatory = isUnitAdmin && !isSubMgr;
boolean unitIsForbidden = !isUnitAdmin && isSubMgr;
if (isUnitToBeAssigned && unitIsForbidden) {
throw new OperationNotPermittedException();
} else if (unitIsMandatory && !isUnitToBeAssigned) {
throw new OperationNotPermittedException();
}
}
if (currentUser.isOrganizationAdmin() || currentUser.isUnitAdmin()) {
newSub.setUserGroup(unit);
}
}
private void autoAssignUserForTriggerProcess(TriggerProcess tp,
VOService product, PlatformUser owner, Subscription newSub)
throws ObjectNotFoundException, OperationNotPermittedException,
ServiceParameterException, SubscriptionStateException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException, ConcurrentModificationException {
Product prod = dataManager
.getReference(Product.class, product.getKey());
TechnicalProduct techProd = prod.getTechnicalProduct();
if (ProvisioningType.SYNCHRONOUS.equals(techProd.getProvisioningType())
&& tp.getTriggerDefinition() != null
&& product.isAutoAssignUserEnabled().booleanValue()
&& newSub.getUsageLicenseForUser(owner) == null) {
// TODO 1. assign users only for SYNCHRONOUS case.
// 2. extract code to another method (more readability).
if (owner != dataManager.getCurrentUser()) {
assignUsersForSubscription(newSub.getSubscriptionId(), product,
owner);
} else {
assignUsersForSubscription(newSub.getSubscriptionId(), product);
}
}
}
List<VOUda> getUdasForCustomer(String targetType, long targetObjectKey,
Organization supplier) throws ValidationException,
ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("targetType", targetType);
UdaTargetType type = UdaAssembler.toUdaTargetType(targetType);
Organization customer = dataManager.getCurrentUser().getOrganization();
UdaAccess udaAccess = new UdaAccess(dataManager, sessionCtx);
List<Uda> udas = udaAccess.getUdasForTypeTargetAndCustomer(
targetObjectKey, type, supplier, customer);
List<VOUda> voUdas = new ArrayList<>();
for (Uda uda : udas) {
voUdas.add(UdaAssembler.toVOUda(uda));
}
return voUdas;
}
void logSubscriptionAttributeForEdit(Subscription sub, List<VOUda> udaList) {
Organization customer = dataManager.getCurrentUser().getOrganization();
for (VOUda voUda : udaList) {
audit.editSubscriptionAndCustomerAttributeByCustomer(dataManager,
customer, sub, voUda.getUdaDefinition().getUdaId(), voUda
.getUdaValue(), voUda.getUdaDefinition()
.getTargetType());
}
}
void logSubscriptionAttributeForCreation(Subscription sub,
List<VOUda> udaList, List<VOUda> customerUdaList) {
Map<String, String> customerAttributesMap = new HashMap<>();
for (VOUda voUda : customerUdaList) {
String parameterName = voUda.getUdaDefinition().getUdaId();
String parameterValue = voUda.getUdaValue();
customerAttributesMap.put(parameterName, parameterValue);
}
for (VOUda voUda : udaList) {
String parameterName = voUda.getUdaDefinition().getUdaId();
String targetType = voUda.getUdaDefinition().getTargetType();
String parameterValue = voUda.getUdaValue();
String defaultValue = voUda.getUdaDefinition().getDefaultValue();
defaultValue = defaultValue == null ? "" : defaultValue;
if (!UdaTargetType.CUSTOMER.toString().equals(targetType)) {
if (!parameterValue.equals(defaultValue)) {
audit.editSubscriptionAndCustomerAttributeByCustomer(
dataManager, null, sub, parameterName,
parameterValue, voUda.getUdaDefinition()
.getTargetType());
}
} else {
String existingValue = customerAttributesMap.get(voUda
.getUdaDefinition().getUdaId());
existingValue = existingValue == null ? "" : existingValue;
Organization customer = dataManager.getCurrentUser()
.getOrganization();
if (!(parameterValue.equals(existingValue) || parameterValue
.equals(defaultValue))) {
audit.editSubscriptionAndCustomerAttributeByCustomer(
dataManager, customer, null, parameterName,
parameterValue, voUda.getUdaDefinition()
.getTargetType());
}
}
}
}
void logSubscriptionOwner(Subscription sub, PlatformUser oldOwner) {
audit.editSubscriptionOwner(dataManager, sub, oldOwner);
}
/**
* Get the subscription attributes that are changed by user
*/
List<VOUda> getUpdatedSubscriptionAttributes(List<VOUda> inputUdaList,
List<Uda> existingUdas) {
Map<String, String> existingAttributesMap = new HashMap<>();
List<VOUda> updatedList = new ArrayList<>();
for (Uda uda : existingUdas) {
existingAttributesMap.put(uda.getUdaDefinition().getUdaId(),
uda.getUdaValue());
}
for (VOUda input : inputUdaList) {
String existingValue = existingAttributesMap.get(input
.getUdaDefinition().getUdaId());
String defaultValue = input.getUdaDefinition().getDefaultValue() == null ? ""
: input.getUdaDefinition().getDefaultValue();
String inputValue = input.getUdaValue() == null ? "" : input
.getUdaValue();
if (existingValue == null && !inputValue.equals(defaultValue)) {
updatedList.add(input);
}
if (existingValue != null && !inputValue.equals(existingValue)) {
updatedList.add(input);
}
}
return updatedList;
}
/**
* Enables the payment types that are enabled for new customer for the
* provided {@link OrganizationReference}.
*
* @param refSuplCust
* the reference to enable the default payment types for
*/
private void enableDefaultPaymentsForCustomer(
OrganizationReference refSuplCust) {
Organization supplier = refSuplCust.getSource();
Organization customer = refSuplCust.getTarget();
Set<OrganizationToRole> roles = customer.getGrantedRoles();
OrganizationRole role = null;
for (OrganizationToRole organizationToRole : roles) {
OrganizationRole tmp = organizationToRole.getOrganizationRole();
if (tmp.getRoleName() == OrganizationRoleType.CUSTOMER) {
role = tmp;
break;
}
}
// the suppliers default configuration
List<OrganizationRefToPaymentType> refs = supplier
.getPaymentTypes(
true,
refSuplCust.getReferenceType() == OrganizationReferenceType.RESELLER_TO_CUSTOMER ? OrganizationRoleType.RESELLER
: OrganizationRoleType.SUPPLIER,
OrganizationRoleType.PLATFORM_OPERATOR.name());
for (OrganizationRefToPaymentType ref : refs) {
OrganizationRefToPaymentType newRef = new OrganizationRefToPaymentType();
newRef.setOrganizationReference(refSuplCust);
newRef.setPaymentType(ref.getPaymentType());
newRef.setOrganizationRole(role);
try {
dataManager.persist(newRef);
} catch (NonUniqueBusinessKeyException e) {
SaaSSystemException sse = new SaaSSystemException(
"Caught NonUniqueBusinessKeyException although there is no business key",
e);
LOG.logError(Log4jLogger.SYSTEM_LOG, sse,
LogMessageIdentifier.ERROR_UNEXPECTED_BK_VIOLATION);
throw sse;
}
refSuplCust.getPaymentTypes().add(newRef);
}
}
/**
* Add users to the subscription assign the users to the subscription, but
* do not inform the product about it at this time (will be done later) We
* assume that the users already exist as platform users ! We start with the
* admins: if a user is in both lists, we just can ignore his entry in
* "users", as he is already entered from "admins" and has the correct
* isAdmin-flag ! We have to ensure that at least 1 user is assigned
*
* @throws ServiceParameterException
* @throws OperationNotPermittedException
* @throws ObjectNotFoundException
* @throws TechnicalServiceOperationException
* @throws TechnicalServiceNotAliveException
*/
private TenantProvisioningResult createInstanceAndAddUsersToSubscription(
TriggerProcess tp, Subscription subscription)
throws ServiceParameterException, ObjectNotFoundException,
OperationNotPermittedException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
List<PlatformUser> addedUsers = new ArrayList<>();
List<UsageLicense> addedUserLicenses = new ArrayList<>();
List<?> users = tp.getParamValueForName(
TriggerProcessParameterName.USERS).getValue(List.class);
if (users != null) {
for (Object o : users) {
VOUsageLicense lic = VOUsageLicense.class.cast(o);
PlatformUser usr = idManager.getPlatformUser(lic.getUser()
.getUserId(), true); // not found? => throws
// ObjectNotFoundException
RoleDefinition role = getAndCheckServiceRole(lic,
subscription.getProduct());
try {
addUserToSubscription(subscription, usr, role);
addedUsers.add(usr);
UsageLicense usageLicenseForUser = subscription
.getUsageLicenseForUser(usr);
// add the user's license to the list for later mail
// sending
if (usageLicenseForUser != null) {
addedUserLicenses.add(usageLicenseForUser);
}
} catch (UserAlreadyAssignedException e) {
// Most probably the user already has been in the users
// list (or he/she is in the list twice)
// Let's ignore it!
// But log this event !
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
LogMessageIdentifier.WARN_USER_APPEAR_MORE_THAN_ONCE,
Long.toString(usr.getKey()),
Long.toString(subscription.getKey()));
}
}
}
boolean directLogin = subscription.getProduct().getTechnicalProduct()
.getAccessType() == ServiceAccessType.DIRECT;
if (!directLogin) {
verifyParameterNamedUser(subscription);
}
// Call tenant provisioning to create instance! Afterwards the
// instance is started as well
TenantProvisioningResult provisioningResult = tenantProvisioning
.createProductInstance(subscription);
if (provisioningResult.isAsyncProvisioning()) {
return provisioningResult;
}
PriceModel pm = subscription.getProduct().getPriceModel();
pm.setProvisioningCompleted(true);
subscription.setActivationDate(subscription.getCreationDate());
activateSubscriptionFirstTime(subscription);
String instanceId = provisioningResult.getProductInstanceId();
subscription.setProductInstanceId(instanceId);
subscription.setAccessInfo(provisioningResult.getAccessInfo());
subscription.setBaseURL(provisioningResult.getBaseUrl());
subscription.setLoginPath(provisioningResult.getLoginPath());
// inform the product about the users
try {
informProductAboutNewUsers(subscription, addedUsers);
} catch (SubscriptionStateException e) {
// should never be reached because state is set to
// active
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_INFORM_PRODUCT_ABOUT_NEW_USER_FAILED);
}
// Send an email to the organization admin. Is performed
// after the save operation to ensure everything worked fine and
// no mail is sent if storing fails.
sendToSubscriptionAddedMail(subscription, addedUserLicenses);
return provisioningResult;
}
/**
* Send the subscription created email to the users assigned to the
* subscription. The mail also includes the access information.
*
* @param subscription
* the created subscription to get the id and access info (url or
* descriptive text) from
* @param usageLicenses
* the usage licenses of the users added to the subscription
*/
private void sendToSubscriptionAddedMail(Subscription subscription,
List<UsageLicense> usageLicenses) {
if (subscription.getStatus() != SubscriptionStatus.ACTIVE) {
return;
}
EmailType emailType = useAccessInfo(subscription) ? EmailType.SUBSCRIPTION_USER_ADDED_ACCESSTYPE_DIRECT
: EmailType.SUBSCRIPTION_USER_ADDED;
Long marketplaceKey = null;
if (subscription.getMarketplace() != null) {
marketplaceKey = Long.valueOf(subscription.getMarketplace()
.getKey());
}
SendMailPayload payload = new SendMailPayload();
for (UsageLicense usageLicense : usageLicenses) {
String accessInfo = getAccessInfo(subscription,
usageLicense.getUser());
if (isUsableAWSAccessInfo(accessInfo)) {
payload.addMailObjectForUser(usageLicense.getUser().getKey(),
EmailType.SUBSCRIPTION_USER_ADDED_ACCESSINFO,
new Object[] { subscription.getSubscriptionId(),
getPublicDNS(accessInfo),
getIPAddress(accessInfo),
getKeyPairName(accessInfo) }, marketplaceKey);
} else {
payload.addMailObjectForUser(usageLicense.getUser().getKey(),
emailType,
new Object[] { subscription.getSubscriptionId(),
accessInfo }, marketplaceKey);
}
}
TaskMessage message = new TaskMessage(SendMailHandler.class, payload);
tqs.sendAllMessages(Collections.singletonList(message));
}
private boolean useAccessInfo(Subscription subscription) {
ServiceAccessType accessType = subscription.getProduct()
.getTechnicalProduct().getAccessType();
return accessType == ServiceAccessType.DIRECT
|| accessType == ServiceAccessType.USER;
}
String getAccessInfo(Subscription subscription, PlatformUser user) {
String accessInfo;
if (useAccessInfo(subscription)) {
accessInfo = subscription.getAccessInfo();
if (accessInfo == null) {
accessInfo = localizer.getLocalizedTextFromDatabase(
user.getLocale(), subscription.getProduct()
.getTechnicalProduct().getKey(),
LocalizedObjectTypes.TEC_PRODUCT_LOGIN_ACCESS_DESC);
if (accessInfo != null) {
accessInfo = accessInfo.replaceAll("<p>", "\n");
accessInfo = accessInfo.replaceAll("</p>", "\n");
}
}
} else {
accessInfo = getSubscriptionUrl(subscription);
}
if (accessInfo == null) {
accessInfo = "";
}
return accessInfo;
}
/**
* Gets the URL to access the subscription.
*
* @param subscription
* the subscription for which we want to know the URL
* @return the URL to access the subscription
*/
String getSubscriptionUrl(Subscription subscription) {
StringBuilder url = new StringBuilder();
String baseUrl = cfgService.getBaseURL();
String technicalProductBaseUrl = subscription.getProduct()
.getTechnicalProduct().getBaseURL();
if (ADMValidator.isHttpsScheme(technicalProductBaseUrl)) {
baseUrl = cfgService.getConfigurationSetting(
ConfigurationKey.BASE_URL_HTTPS,
Configuration.GLOBAL_CONTEXT).getValue();
}
url.append(baseUrl);
if (url.length() == 0 || url.charAt(url.length() - 1) != '/') {
url.append('/');
}
url.append("opt/");
url.append(Long.toHexString(subscription.getKey()));
url.append('/');
return url.toString();
}
/**
* Creates the 'allowing on behalf acting reference' between the technology
* provider and the customer's organization.
*
* @throws NonUniqueBusinessKeyException
*/
private void createAllowOnBehalfActingReference(Subscription subscription)
throws NonUniqueBusinessKeyException {
// fetch the technical product
TechnicalProduct technicalProduct = subscription.getProduct()
.getTechnicalProduct();
// if allow on behalf acting is true
if (technicalProduct.isAllowingOnBehalfActing()) {
// get source (techn. prov.) and target (supplier) organization
Organization source = technicalProduct.getOrganization();
Organization target = dataManager.getCurrentUser()
.getOrganization();
// check if a reference does not already exist
if (!isOnBehalfReferenceExisting(source, target)) {
// create and persist reference
OrganizationReference reference = new OrganizationReference(
source, target,
OrganizationReferenceType.ON_BEHALF_ACTING);
dataManager.persist(reference);
}
}
}
private boolean isOnBehalfReferenceExisting(
Organization sourceOrganization, Organization targetOrganization) {
return getOrganizationReference(sourceOrganization, targetOrganization) != null;
}
private OrganizationReference getOrganizationReference(
Organization sourceOrganization, Organization targetOrganization) {
for (OrganizationReference reference : targetOrganization
.getSourcesForType(OrganizationReferenceType.ON_BEHALF_ACTING)) {
if (reference.getSource().getKey() == sourceOrganization.getKey()
&& reference.getTargetKey() == targetOrganization.getKey()) {
return reference;
}
}
return null;
}
private void sendSubscriptionCreatedMailToAdministrators(
Subscription subscription, boolean actingOnBehalf) {
EmailType emailType = actingOnBehalf ? EmailType.SUBSCRIPTION_CREATED_ON_BEHALF_ACTING
: EmailType.SUBSCRIPTION_CREATED;
Long marketplaceKey = null;
if (subscription.getMarketplace() != null) {
marketplaceKey = Long.valueOf(subscription.getMarketplace()
.getKey());
}
SendMailPayload payload = new SendMailPayload();
List<PlatformUser> users = manageBean
.getCustomerAdminsAndSubscriptionOwner(subscription);
for (PlatformUser user : users) {
payload.addMailObjectForUser(user.getKey(), emailType,
new Object[] { subscription.getSubscriptionId() },
marketplaceKey);
}
TaskMessage message = new TaskMessage(SendMailHandler.class, payload);
tqs.sendAllMessages(Collections.singletonList(message));
}
/**
* Validates that subscribing to the given product is possible with the
* specified subscription data.
*
* @param subscription
* The subscription to be created.
* @param product
* The product to subscribe to.
* @param voBillingContact
* @throws ValidationException
* Thrown in case the validation of the subscription failed.
* @throws ObjectNotFoundException
* Thrown in case the product could not be found.
* @throws OperationNotPermittedException
* Thrown in case the user is not permitted to perform this
* operation.
* @throws ServiceChangedException
* Thrown in case the product has been modified in the meantime.
* @throws PriceModelException
* Thrown in case the product is not useable as it has no price
* model.
* @throws PaymentInformationException
* Thrown in case the product is chargeable but the customer
* does not have a payment information stored.
* @throws ConcurrentModificationException
*/
private void validateSettingsForSubscribing(VOSubscription subscription,
VOService product, VOPaymentInfo paymentInfo,
VOBillingContact voBillingContact) throws ValidationException,
ObjectNotFoundException, OperationNotPermittedException,
ServiceChangedException, PriceModelException,
PaymentInformationException, ConcurrentModificationException {
String subscriptionId = subscription.getSubscriptionId();
BLValidator.isId("subscriptionId", subscriptionId, true);
String pon = subscription.getPurchaseOrderNumber();
BLValidator.isDescription("purchaseOrderNumber", pon, false);
Product productTemplate = dataManager.getReference(Product.class,
product.getKey());
// check product and org settings
Organization targetCustomer = productTemplate.getTargetCustomer();
PlatformUser currentUser = dataManager.getCurrentUser();
Organization organization = currentUser.getOrganization();
if (targetCustomer == null) {
// if it is no customer specific product, check if we have one
// for the subscriber
List<Product> resultList = getProductDao().getCopyForCustomer(
productTemplate, organization);
if (resultList.size() > 0) {
ServiceChangedException sce = new ServiceChangedException(
ServiceChangedException.Reason.SERVICE_MODIFIED);
LOG.logWarn(
Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
sce,
LogMessageIdentifier.WARN_CUSTOMER_MUST_SUBSCRIBE_SPECIFIC_PRODUCT,
organization.getOrganizationId(), productTemplate
.getProductId(), resultList.get(0)
.getProductId());
throw sce;
}
} else if (organization.getKey() != targetCustomer.getKey()) {
// if it is a specific one but not specified for the subscriber
String message = String
.format("Customer specific product '%s' is not specified for customer '%s'.",
productTemplate.getProductId(),
organization.getOrganizationId());
OperationNotPermittedException onp = new OperationNotPermittedException(
message);
LOG.logWarn(
Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
onp,
LogMessageIdentifier.WARN_CUSTOMER_SPECIFIC_PRODUCT_NOT_FOR_THE_CUSTOMER,
productTemplate.getProductId(),
organization.getOrganizationId());
throw onp;
}
checkIfProductIsUptodate(productTemplate, product);
// now check the price model related to the product; if it is
// chargeable, the organization must have specified a payment
// information. If he has not, throw an exception
PriceModel priceModel = productTemplate.getPriceModel();
if (priceModel == null
&& productTemplate.getType() == ServiceType.PARTNER_TEMPLATE) {
priceModel = productTemplate.getTemplate().getPriceModel();
}
if (priceModel == null) {
PriceModelException mpme = new PriceModelException(
PriceModelException.Reason.NOT_DEFINED);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, mpme,
LogMessageIdentifier.WARN_SUBSCRIBE_PRODUCT_FAILED,
Long.toString(productTemplate.getKey()));
throw mpme;
}
if (priceModel.isChargeable()) {
PaymentDataValidator.validateNotNull(paymentInfo, voBillingContact);
PaymentInfo pi = dataManager.getReference(PaymentInfo.class,
paymentInfo.getKey());
BillingContact bc = dataManager.getReference(BillingContact.class,
voBillingContact.getKey());
validatePaymentInfoAndBillingContact(pi, bc, paymentInfo,
voBillingContact);
PermissionCheck.owns(pi, organization, LOG);
PermissionCheck.owns(bc, organization, LOG);
PaymentDataValidator.validatePaymentTypeSupportedBySupplier(
organization, productTemplate, pi.getPaymentType());
PaymentDataValidator.validatePaymentInfoDataForUsage(pi);
}
}
UserGroup getUnit(long unitKey, String unitName, long organizationKey)
throws ObjectNotFoundException {
UserGroup unit = null;
if (unitKey == 0L) {
if (unitName == null || unitName.trim().length() == 0) {
return null;
}
unit = new UserGroup();
unit.setName(unitName);
unit.setOrganization_tkey(organizationKey);
unit = (UserGroup) dataManager.getReferenceByBusinessKey(unit);
} else {
try {
unit = dataManager.getReference(UserGroup.class, unitKey);
if (unit.getOrganization_tkey() != organizationKey) {
throw new ObjectNotFoundException(
"The unit does not belong to your organization.");
}
} catch (ObjectNotFoundException e) {
e.setMessageParams(new String[] { unitName });
throw e;
}
}
return unit;
}
private void checkIfServiceAvailable(long productKey, String productId,
PlatformUser currentUser) throws OperationNotPermittedException,
ObjectNotFoundException {
if (currentUser.isOrganizationAdmin()) {
return;
}
List<Long> invisibleProductKeys = userGroupService
.getInvisibleProductKeysForUser(currentUser.getKey());
if (invisibleProductKeys.contains(Long.valueOf(productKey))) {
String message = String.format("Service '%s' is not avalible.",
productId);
OperationNotPermittedException onp = new OperationNotPermittedException(
message);
LOG.logWarn(Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG, onp,
LogMessageIdentifier.WARN_SERVICE_NOT_AVAILABLE, productId);
throw onp;
}
}
/**
* Checks if there already exists a subscription to the technical service to
* which the specified VOService belongs to.
*
* @param product
* the VOService for which to check if already has active
* subscriptions.
*/
private void checkIfSubscriptionAlreadyExists(VOService product)
throws SubscriptionAlreadyExistsException, ObjectNotFoundException {
// Fetch the technical product to which the defined product belongs to.
Product prod = dataManager
.getReference(Product.class, product.getKey());
TechnicalProduct technicalProduct = prod.getTechnicalProduct();
// Only in case one subscription is allowed check the number of already
// existing subscriptions.
if (technicalProduct.isOnlyOneSubscriptionAllowed()) {
Organization organization = dataManager.getCurrentUser()
.getOrganization();
Long numberOfSubscriptions = getSubscriptionDao()
.getNumberOfVisibleSubscriptions(technicalProduct,
organization);
// If there are already subscriptions to the technical product
// based on the product, throw an exception.
if (numberOfSubscriptions.longValue() > 0) {
Object[] params = new Object[] { prod.getProductId() };
SubscriptionAlreadyExistsException subAlreadyExistsException = new SubscriptionAlreadyExistsException(
params);
LOG.logWarn(
Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
subAlreadyExistsException,
LogMessageIdentifier.WARN_USER_SUBSCRIBE_SERVICE_FAILED_ONLY_ONE_ALLOWED,
Long.toString(dataManager.getCurrentUser().getKey()),
Long.toString(prod.getKey()),
Long.toString(organization.getKey()));
throw subAlreadyExistsException;
}
}
}
/**
* Checks if there already exists a subscription with the same subscriptions
* name for this Organization.
*
* @param currentUser
* current platform user
* @param voSubscription
* subscription
* @throws NonUniqueBusinessKeyException
*/
private void verifyIdAndKeyUniqueness(PlatformUser currentUser,
VOSubscription voSubscription) throws NonUniqueBusinessKeyException {
Subscription newSubscription = new Subscription();
newSubscription.setOrganizationKey(currentUser.getOrganization()
.getKey());
newSubscription.setSubscriptionId(voSubscription.getSubscriptionId());
dataManager.validateBusinessKeyUniqueness(newSubscription);
}
/**
* Its responsible for updating the values for the subscribed product from
* the parameter list.
*
* @param product
* the product to update
* @param parameters
* the list of parameters
* @param subscription
* - target subscription
*/
List<Parameter> updateConfiguredParameterValues(Product product,
List<VOParameter> parameters, Subscription subscription) {
Map<String, Parameter> paramMap = new HashMap<>();
if (product.getParameterSet() != null) {
for (Parameter parameter : product.getParameterSet()
.getParameters()) {
paramMap.put(parameter.getParameterDefinition()
.getParameterId(), parameter);
}
}
// reload all the parameter values from old subscription
if (subscription != null && subscription.getParameterSet() != null
&& !subscription.getProduct().equals(product)) {
List<Parameter> params = subscription.getParameterSet()
.getParameters();
if (params != null && params.size() > 0) {
for (Parameter param : params) {
String parameterId = param.getParameterDefinition()
.getParameterId();
Parameter uParam = paramMap.get(parameterId);
if (uParam != null) {
uParam.setValue(param.getValue());
}
}
}
}
List<Parameter> modifiedParametesForLog = new ArrayList<>();
for (VOParameter voParameter : parameters) {
String parameterID = voParameter.getParameterDefinition()
.getParameterId();
Parameter param = paramMap.get(parameterID);
if (param != null) {
String oldValue = param.getValue();
param.setValue(voParameter.getValue());
String defaultValue = param.getParameterDefinition()
.getDefaultValue();
if ((oldValue != null && !oldValue.equals(param.getValue()))
|| (oldValue == null && param.getValue() != null && !param
.getValue().equals(defaultValue))) {
modifiedParametesForLog.add(param);
}
}
}
dataManager.flush();
return modifiedParametesForLog;
}
/**
* If a product with a customer specific price model, was copied the
* subscription specific one would refer to the template's one when getting
* localized values - so we have to copy those ones from the original price
* model
*
* @param targetProduct
* @param sourceProduct
*/
private void copyLocalizedPricemodelValues(Product targetProduct,
Product sourceProduct) {
List<VOLocalizedText> localizedValues;
final PriceModel priceModelTarget = targetProduct.getPriceModel();
final PriceModel priceModelSource = sourceProduct.getType() == ServiceType.PARTNER_TEMPLATE ? sourceProduct
.getTemplate().getPriceModel() : sourceProduct.getPriceModel();
if ((priceModelTarget != null) && (priceModelSource != null)) {
long targetKey = targetProduct.getPriceModel().getKey();
long sourceKey = priceModelSource.getKey();
localizedValues = localizer.getLocalizedValues(sourceKey,
LocalizedObjectTypes.PRICEMODEL_DESCRIPTION);
if (localizedValues != null && !localizedValues.isEmpty()) {
localizer.storeLocalizedResources(targetKey,
LocalizedObjectTypes.PRICEMODEL_DESCRIPTION,
localizedValues);
}
// license copy
if (sourceProduct.getVendor().getGrantedRoleTypes()
.contains(OrganizationRoleType.RESELLER)) {
localizedValues = localizer.getLocalizedValues(
sourceProduct.getKey(),
LocalizedObjectTypes.RESELLER_PRICEMODEL_LICENSE);
} else {
localizedValues = localizer.getLocalizedValues(sourceKey,
LocalizedObjectTypes.PRICEMODEL_LICENSE);
}
if (localizedValues != null && !localizedValues.isEmpty()) {
localizer.storeLocalizedResources(targetKey,
LocalizedObjectTypes.PRICEMODEL_LICENSE,
localizedValues);
}
}
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public boolean addRevokeUser(String subscriptionId,
List<VOUsageLicense> usersToBeAdded, List<VOUser> usersToBeRevoked)
throws ObjectNotFoundException, ServiceParameterException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationNotPermittedException,
ConcurrentModificationException, OperationPendingException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
Subscription sub = manageBean.checkSubscriptionOwner(subscriptionId, 0);
stateValidator.checkAddRevokeUserAllowed(sub);
// validation
if (usersToBeAdded != null) {
for (VOUsageLicense lic : usersToBeAdded) {
try {
PlatformUser user = dataManager.getReference(
PlatformUser.class, lic.getUser().getKey());
getAndCheckServiceRole(lic, sub.getProduct());
// fill user ID for trigger process
lic.getUser().setUserId(user.getUserId());
} catch (ObjectNotFoundException e) {
throw new ObjectNotFoundException(
DomainObjectException.ClassEnum.USER,
String.valueOf(lic.getUser().getUserId()));
}
}
}
if (usersToBeRevoked != null) {
for (VOUser entry : usersToBeRevoked) {
try {
PlatformUser user = dataManager.getReference(
PlatformUser.class, entry.getKey());
// fill user ID for trigger process
entry.setUserId(user.getUserId());
} catch (ObjectNotFoundException e) {
throw new ObjectNotFoundException(
DomainObjectException.ClassEnum.USER,
String.valueOf(entry.getUserId()));
}
}
}
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
List<TriggerProcessIdentifier> pendingAddRevokeUsers = validator
.getPendingAddRevokeUsers(subscriptionId, usersToBeAdded,
usersToBeRevoked);
if (!pendingAddRevokeUsers.isEmpty()) {
String userIds = determineUserIds(pendingAddRevokeUsers);
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request for subscription '%s' to add or revoke the users: %s",
subscriptionId, userIds),
ReasonEnum.ADD_REVOKE_USER, new Object[] { subscriptionId,
userIds });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_ADD_REVOKE_USER_FAILED_DUE_TO_TRIGGER_CONFLICT,
subscriptionId);
throw ope;
}
validateTriggerProcessForSubscription(sub);
// now send a suspending message for the processing
TriggerMessage message = new TriggerMessage(TriggerType.ADD_REVOKE_USER);
List<TriggerProcessMessageData> list = triggerQS
.sendSuspendingMessages(Collections.singletonList(message));
TriggerProcess proc = list.get(0).getTrigger();
proc.addTriggerProcessParameter(TriggerProcessParameterName.OBJECT_ID,
subscriptionId);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscriptionId);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.USERS_TO_ADD, usersToBeAdded);
proc.addTriggerProcessParameter(
TriggerProcessParameterName.USERS_TO_REVOKE, usersToBeRevoked);
try {
// if processing is not suspended, call finishing method
TriggerDefinition triggerDefinition = proc.getTriggerDefinition();
if (triggerDefinition == null) {
addRevokeUserInt(proc);
return true;
} else if (triggerDefinition.isSuspendProcess()) {
proc.setTriggerProcessIdentifiers(TriggerProcessIdentifiers
.createAddRevokeUser(dataManager,
TriggerType.ADD_REVOKE_USER, subscriptionId,
usersToBeAdded, usersToBeRevoked));
dataManager.merge(proc);
}
} catch (ObjectNotFoundException | SubscriptionStateException
| TechnicalServiceNotAliveException
| TechnicalServiceOperationException e) {
sessionCtx.setRollbackOnly();
throw e;
}
return false;
}
void validateTriggerProcessForSubscription(Subscription subscription)
throws OperationPendingException {
validateTriggerProcessForUnsubscribeFromService(subscription
.getSubscriptionId());
validateTriggerProcessForUpgradeSubscriptionBySubscriptionKey(
subscription.getKey(), subscription.getSubscriptionId());
validateTriggerProcessForModifySubscriptionBySubscriptionKey(
subscription.getKey(), subscription.getSubscriptionId());
}
/**
* Determines the user identifiers that are contained in the passed in list
* of process identifiers.
*
* @param pendingAddRevokeUsers
* The list of process identifiers to check.
* @return The user identifiers.
*/
private String determineUserIds(
List<TriggerProcessIdentifier> pendingAddRevokeUsers) {
StringBuilder userIds = new StringBuilder();
for (TriggerProcessIdentifier id : pendingAddRevokeUsers) {
if (userIds.length() != 0) {
userIds.append(", ");
}
if (TriggerProcessIdentifierName.USER_TO_ADD.equals(id.getName())
|| TriggerProcessIdentifierName.USER_TO_REVOKE.equals(id
.getName())) {
userIds.append(id.getValue());
}
}
return userIds.toString();
}
/**
* Tries to read the service role that should be assigned (if not
* <code>null</code>). If the role exists, it will be checked if it belongs
* to the product's technical product.
*
* @param lic
* the {@link VOUsageLicense}
* @param prod
* the {@link Product}
* @return <code>null</code> if no service roles are defined on the
* technical product and the specified one on the
* {@link VOUsageLicense} is <code>null</code>. Otherwise the read
* role will be returned if valid
* @throws ObjectNotFoundException
* in case the role wasn't found.
* @throws OperationNotPermittedException
* in case the read role doesn't belong to the subscriptions
* technical product or no role is specified when service roles
* have to be used on the technical product
*/
private RoleDefinition getAndCheckServiceRole(VOUsageLicense lic,
Product prod) throws ObjectNotFoundException,
OperationNotPermittedException {
TechnicalProduct tp = prod.getTechnicalProduct();
List<RoleDefinition> roles = tp.getRoleDefinitions();
if (roles == null || roles.isEmpty()) {
lic.setRoleDefinition(null);
return null;
}
if (lic.getRoleDefinition() == null) {
String message = "User assignment to technical service '%s' without service role not possible.";
OperationNotPermittedException onp = new OperationNotPermittedException(
String.format(message, Long.valueOf(tp.getKey())));
LOG.logError(
Log4jLogger.SYSTEM_LOG,
onp,
LogMessageIdentifier.ERROR_USER_ASSIGNMENT_TO_TECHNICAL_SERVICE_FAILED_NO_SERVICE_ROLE,
Long.toString(tp.getKey()));
throw onp;
}
RoleDefinition role = dataManager.getReference(RoleDefinition.class,
lic.getRoleDefinition().getKey());
for (RoleDefinition roleDefinition : roles) {
if (role.getKey() == roleDefinition.getKey()) {
return role;
}
}
String message = "Role '%s' is not defined on technical service '%s'";
OperationNotPermittedException onp = new OperationNotPermittedException(
String.format(message, Long.valueOf(role.getKey()),
Long.valueOf(tp.getKey())));
LOG.logError(Log4jLogger.SYSTEM_LOG, onp,
LogMessageIdentifier.ERROR_NO_ROLE_FOR_TECHNICAL_SERVICE,
Long.toString(role.getKey()), Long.toString(tp.getKey()));
throw onp;
}
@Override
@RolesAllowed("ORGANIZATION_ADMIN")
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void addRevokeUserInt(TriggerProcess tp)
throws ObjectNotFoundException, ServiceParameterException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationNotPermittedException,
ConcurrentModificationException {
TriggerProcessParameter mod;
mod = tp.getParamValueForName(TriggerProcessParameterName.SUBSCRIPTION);
String subscriptionId = mod.getValue(String.class);
mod = tp.getParamValueForName(TriggerProcessParameterName.USERS_TO_ADD);
List<?> usersToBeAdded = mod.getValue(List.class);
mod = tp.getParamValueForName(TriggerProcessParameterName.USERS_TO_REVOKE);
List<?> usersToBeRevoked = mod.getValue(List.class);
// Try to find the subscription
Subscription subscription = manageBean.loadSubscription(subscriptionId,
0);
List<UsageLicense> addedUsersLicenses = new ArrayList<>();
List<PlatformUser> usersToAdd = new ArrayList<>();
// loop for adding users
if (usersToBeAdded != null) {
for (Object entry : usersToBeAdded) {
final VOUsageLicense lic = (VOUsageLicense) entry;
final PlatformUser usr = dataManager.getReference(
PlatformUser.class, lic.getUser().getKey());
final RoleDefinition roleDef = getAndCheckServiceRole(lic,
subscription.getProduct());
final UsageLicense usageLicenseForUser = subscription
.getUsageLicenseForUser(usr);
try {
if (usageLicenseForUser == null) {
// Create a new usage License
final UsageLicense newUsageLicense = addUserToSubscription(
subscription, usr, roleDef);
usersToAdd.add(usr);
// store the new user's licenses for later mail sending
addedUsersLicenses.add(newUsageLicense);
} else {
// Update an existing usage license:
BaseAssembler.verifyVersionAndKey(usageLicenseForUser,
lic);
modifyUserRole(subscription, usr, roleDef);
}
} catch (UserNotAssignedException
| UserAlreadyAssignedException e) {
// Must not happen here
throw new AssertionError(e);
}
}
}
// loop for revoking users
if (usersToBeRevoked != null) {
List<PlatformUser> platformUsers = new ArrayList<>();
for (Object qryUsr : usersToBeRevoked) {
PlatformUser usr = dataManager.getReference(PlatformUser.class,
VOUser.class.cast(qryUsr).getKey());
platformUsers.add(usr);
}
revokeUserFromSubscription(subscription, platformUsers);
}
verifyParameterNamedUser(subscription);
informProductAboutNewUsers(subscription, usersToAdd);
sendToSubscriptionAddedMail(subscription, addedUsersLicenses);
// notify all listeners
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.ADD_REVOKE_USER, tp.getTriggerProcessParameters(),
dataManager.getCurrentUser().getOrganization()));
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void modifyUserRole(Subscription subscription, PlatformUser usr,
RoleDefinition roleDef) throws SubscriptionStateException,
UserNotAssignedException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
stateValidator.checkModifyUserRoleAllowed(subscription);
UsageLicense license = subscription.getUsageLicenseForUser(usr);
RoleDefinition oldRoleDef = null;
if (license != null) {
oldRoleDef = license.getRoleDefinition();
if (oldRoleDef == roleDef) {
// nothing to do - role not changed; avoid sending of mail and
// notification of service
return;
}
}
UsageLicense targetLicense = subscription.changeRole(usr, roleDef);
// Inform application about changed role
if (canModifyApplicationUsers(subscription) && targetLicense != null) {
appManager.updateUsers(subscription,
Collections.singletonList(targetLicense));
// log deassign user role for service
audit.deassignUserRoleForService(dataManager, subscription, usr,
oldRoleDef);
// log assign user role for service
audit.assignUserRoleForService(dataManager, subscription, usr,
roleDef);
}
try {
String accessInfo = targetLicense == null ? "" : getAccessInfo(
subscription, targetLicense.getUser());
commService
.sendMail(usr, EmailType.SUBSCRIPTION_ACCESS_GRANTED,
new Object[] { subscription.getSubscriptionId(),
accessInfo }, subscription.getMarketplace());
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_GRANT_ROLE_IN_SUBSCRIPTION_CONFIRMING_FAILED);
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public UsageLicense addUserToSubscription(Subscription subscription,
PlatformUser user, RoleDefinition serviceRole)
throws UserAlreadyAssignedException {
final UsageLicense usageLicense = subscription.addUser(user,
serviceRole);
audit.assignUserToSubscription(dataManager, subscription, usageLicense);
return usageLicense;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void revokeUserFromSubscription(final Subscription subscription,
final List<PlatformUser> users) throws SubscriptionStateException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
stateValidator.checkAddRevokeUserAllowed(subscription);
revokeUserFromSubscriptionInt(subscription, users);
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void revokeUserFromSubscriptionInt(final Subscription subscription,
final List<PlatformUser> users)
throws TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
List<UsageLicense> usageLicenses = doRevokeUserFromSubscriptionInt(
subscription, users);
audit.deassignUserFromSubscription(dataManager, subscription,
usageLicenses);
}
/**
* Worker method for revokeUserFromSubscription, allows to ignore
* lastUser-Check (only for use in unsubscribe)
*
* @param subscription
* The subscription to be changed.
* @param users
* The users to be revoked from the subscription.
* @return the list of usage licenses
* @throws TechnicalServiceNotAliveException
* @throws TechnicalServiceOperationException
*/
private List<UsageLicense> doRevokeUserFromSubscriptionInt(
Subscription subscription, List<PlatformUser> users)
throws TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
List<UsageLicense> licenseList = new ArrayList<>();
for (PlatformUser user : users) {
UsageLicense license = subscription.revokeUser(user);
// if the subscription is invalid (e.g. instance creation
// failed) no call to the application is performed
if (isValidSubscription(subscription) && license != null) {
licenseList.add(license);
}
}
// Bug 9998. while the subscription is still pending, no call to
// ProvisioningService.deleteUsers(String, List<User>) has to be
// performed.
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
appManager.deleteUsers(subscription, licenseList);
}
for (UsageLicense license : licenseList) {
// explicitly remove the user's usage license
if (license != null) {
dataManager.remove(license);
}
dataManager.flush();
}
if (subscription.getStatus() == SubscriptionStatus.ACTIVE
&& subscription.getProduct().getTechnicalProduct()
.getAccessType() != ServiceAccessType.DIRECT) {
// as the user gets no mail when being added to a pending
// subscription, the notification about the removal will also not be
// sent.
Long marketplaceKey = null;
if (subscription.getMarketplace() != null) {
marketplaceKey = Long.valueOf(subscription.getMarketplace()
.getKey());
}
SendMailPayload payload = new SendMailPayload();
for (PlatformUser user : users) {
payload.addMailObjectForUser(user.getKey(),
EmailType.SUBSCRIPTION_USER_REMOVED,
new Object[] { subscription.getSubscriptionId() },
marketplaceKey);
}
TaskMessage message = new TaskMessage(SendMailHandler.class,
payload);
tqs.sendAllMessages(Collections.singletonList(message));
}
return licenseList;
}
private boolean isValidSubscription(Subscription subscription) {
return subscription.getStatus() != SubscriptionStatus.INVALID;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<Subscription> getSubscriptionsForUserInt(PlatformUser user) {
return getSubscriptionDao().getSubscriptionsForUser(user);
}
@Override
@RolesAllowed("ORGANIZATION_ADMIN")
public List<VOUserSubscription> getSubscriptionsForUser(VOUser user)
throws ObjectNotFoundException, OperationNotPermittedException {
return getSubscriptionsForUser(user, PerformanceHint.ALL_FIELDS);
}
@RolesAllowed("ORGANIZATION_ADMIN")
public List<VOUserSubscription> getSubscriptionsForUser(VOUser user,
PerformanceHint performanceHint) throws ObjectNotFoundException,
OperationNotPermittedException {
ArgumentValidator.notNull("user", user);
PlatformUser platformUser = idManager.getPlatformUser(user.getUserId(),
true);
LocalizerFacade facade = new LocalizerFacade(localizer,
platformUser.getLocale());
List<Subscription> subs = getSubscriptionsForUserInt(platformUser);
ArrayList<VOUserSubscription> result = new ArrayList<>();
for (Subscription sub : subs) {
VOUserSubscription voSub = SubscriptionAssembler
.toVOUserSubscription(sub, platformUser, facade,
performanceHint);
result.add(voSub);
}
return result;
}
@Override
public List<VOUserSubscription> getSubscriptionsForCurrentUser() {
ArrayList<VOUserSubscription> result = new ArrayList<>();
PlatformUser user = dataManager.getCurrentUser();
List<Subscription> subs = getSubscriptionsForUserInt(user);
LocalizerFacade facade = new LocalizerFacade(localizer,
user.getLocale());
SubscriptionAssembler.prefetchData(subs, facade);
for (Subscription sub : subs) {
VOUserSubscription voSub = SubscriptionAssembler
.toVOUserSubscription(sub, user, facade);
result.add(voSub);
}
return result;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VOSubscription> getSubscriptionsForOrganization() {
return getSubscriptionsForOrganizationWithFilter(null);
}
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VOSubscription> getSubscriptionsForOrganization(
PerformanceHint performanceHint) {
return getSubscriptionsForOrganizationWithFilter(null, performanceHint);
}
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER", "UNIT_ADMINISTRATOR" })
public List<VOSubscription> getAllSubscriptionsForOrganization(
PerformanceHint performanceHint) {
ArrayList<VOSubscription> result = new ArrayList<>();
List<Subscription> subscriptions = subscriptionListService
.getAllSubscriptionsForOrganization();
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
for (Subscription sub : subscriptions) {
VOSubscription voSub = SubscriptionAssembler.toVOSubscription(sub,
facade, performanceHint);
result.add(voSub);
}
return result;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VOSubscription> getSubscriptionsForOrganizationWithFilter(
Set<SubscriptionStatus> requiredStatus) {
return getSubscriptionsForOrganizationWithFilter(requiredStatus,
PerformanceHint.ALL_FIELDS);
}
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VOSubscription> getSubscriptionsForOrganizationWithFilter(
Set<SubscriptionStatus> requiredStatus,
PerformanceHint performanceHint) {
ArrayList<VOSubscription> result = new ArrayList<>();
// load all subscriptions
List<Subscription> subs = subscriptionListService
.getSubscriptionsForOrganization(requiredStatus);
// create transfer objects
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
for (Subscription sub : subs) {
VOSubscription voSub = SubscriptionAssembler.toVOSubscription(sub,
facade, performanceHint);
result.add(voSub);
}
return result;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public boolean validateSubscriptionIdForOrganization(String subscriptionId) {
// load all subscriptions
List<Subscription> subs = subscriptionListService
.getSubscriptionsForOrganization(null);
boolean subscriptionIdAlreadyExists = false;
for (Subscription sub : subs) {
if (sub.getSubscriptionId().equals(subscriptionId)) {
subscriptionIdAlreadyExists = true;
break;
}
}
return subscriptionIdAlreadyExists;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public VOSubscriptionDetails getSubscriptionDetails(String subscriptionId)
throws ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
Subscription subscription = manageBean.checkSubscriptionOwner(
subscriptionId, 0);
return getSubscriptionDetails(subscription);
}
@Override
public VOSubscriptionDetails getSubscriptionDetails(long subscriptionKey)
throws ObjectNotFoundException, OperationNotPermittedException {
Subscription subscription = manageBean.checkSubscriptionOwner(null,
subscriptionKey);
return getSubscriptionDetails(subscription);
}
private VOSubscriptionDetails getSubscriptionDetails(
Subscription subscription) {
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
return SubscriptionAssembler.toVOSubscriptionDetails(subscription,
facade);
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public boolean unsubscribeFromService(String subscriptionId)
throws ObjectNotFoundException, SubscriptionStillActiveException,
SubscriptionStateException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException, OperationPendingException,
OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
manageBean.checkSubscriptionOwner(subscriptionId, 0);
// Find the subscription and validate if operation can be performed
validateSubsciptionForUnsubscribe(subscriptionId);
validateTriggerProcessForUnsubscribeFromService(subscriptionId);
TriggerProcess triggerProcess = createTriggerProcessForUnsubscribeFromService(subscriptionId);
TriggerDefinition triggerDefinition = triggerProcess
.getTriggerDefinition();
if (triggerDefinition == null) {
try {
unsubscribeFromServiceInt(triggerProcess);
return true;
} catch (ObjectNotFoundException | SubscriptionStillActiveException
| SubscriptionStateException
| TechnicalServiceNotAliveException
| TechnicalServiceOperationException e) {
sessionCtx.setRollbackOnly();
throw e;
}
} else if (triggerDefinition.isSuspendProcess()) {
triggerProcess
.setTriggerProcessIdentifiers(TriggerProcessIdentifiers
.createUnsubscribeFromService(dataManager,
TriggerType.UNSUBSCRIBE_FROM_SERVICE,
subscriptionId));
dataManager.merge(triggerProcess);
}
return false;
}
/**
* @param subscriptionId
* @return
*/
private TriggerProcess createTriggerProcessForUnsubscribeFromService(
String subscriptionId) {
TriggerMessage message = new TriggerMessage(
TriggerType.UNSUBSCRIBE_FROM_SERVICE);
List<TriggerProcessMessageData> list = triggerQS
.sendSuspendingMessages(Collections.singletonList(message));
TriggerProcess triggerProcess = list.get(0).getTrigger();
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.OBJECT_ID, subscriptionId);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscriptionId);
return triggerProcess;
}
private void validateTriggerProcessForUnsubscribeFromService(
String subscriptionId) throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
if (validator.isSubscribeOrUnsubscribeServicePending(subscriptionId)) {
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to unsubscribe from the subscription or create a subscription with identifier '%s'",
subscriptionId),
ReasonEnum.UNSUBSCRIBE_FROM_SERVICE,
new Object[] { subscriptionId });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_UNSUBSCRIBE_FROM_SERVICE_FAILED_DUE_TO_TRIGGER_CONFLICT,
subscriptionId);
throw ope;
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void unsubscribeFromServiceInt(TriggerProcess tp)
throws ObjectNotFoundException, SubscriptionStateException,
SubscriptionStillActiveException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
String subId = tp.getParamValueForName(
TriggerProcessParameterName.SUBSCRIPTION)
.getValue(String.class);
Subscription subscription = validateSubsciptionForUnsubscribe(subId);
stopInstance(subscription);
unsubscribe(subscription);
manageBean.removeUsageLicenses(subscription);
operationRecordBean.removeOperationsForSubscription(subscription
.getKey());
// rename the subscription as last step because id is still used for
// exceptions and mails rename to allow the reuse of the id
final String oldSubscriptionId = subscription.getSubscriptionId();
subscription.setSubscriptionId(String.valueOf(System
.currentTimeMillis()));
boolean removed = removeOnBehalfActingReference(subscription);
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.UNSUBSCRIBE_FROM_SERVICE, tp
.getTriggerProcessParameters(), dataManager
.getCurrentUser().getOrganization()));
tp.addTriggerProcessParameter(TriggerProcessParameterName.SUBSCRIPTION,
buildNotification(oldSubscriptionId));
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.SUBSCRIPTION_TERMINATION, tp
.getTriggerProcessParameters(), subscription
.getProduct().getVendor()));
sendConfirmDeactivationEmail(removed, oldSubscriptionId, subscription);
}
void unsubscribe(Subscription subscription) {
// delete product
final Product product = subscription.getProduct();
product.setStatus(ServiceStatus.DELETED);
final Product asyncTempProduct = subscription.getAsyncTempProduct();
if (asyncTempProduct != null) {
subscription.setAsyncTempProduct(null);
dataManager.remove(asyncTempProduct);
}
modUpgBean.deleteModifiedEntityForSubscription(subscription);
// deactivate subscription
subscription.setStatus(SubscriptionStatus.DEACTIVATED);
long txTime = DateFactory.getInstance().getTransactionTime();
subscription.setDeactivationDate(Long.valueOf(txTime));
// log
audit.unsubscribeFromService(dataManager, subscription);
}
/**
* @param subscription
*/
private void stopInstance(Subscription subscription) {
boolean stopInstance = subscription.getStatus() != SubscriptionStatus.INVALID;
if (stopInstance) {
try {
appManager.deleteInstance(subscription);
} catch (SaaSApplicationException e) {
LOG.logError(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.ERROR_UNSUBSCRIBE_SUBSCRIPTION_FAILED,
Long.toString(subscription.getKey()));
manageBean.sendTechnicalServiceErrorMail(subscription);
}
}
}
private VONotification buildNotification(String subscriptionId) {
VONotificationBuilder builder = new VONotificationBuilder();
return builder.addParameter(VOProperty.SUBSCRIPTION_SUBSCRIPTION_ID,
subscriptionId).build();
}
private boolean removeOnBehalfActingReference(Subscription subscription) {
// execute isLastSubscription named query
Long isLastSubscription = getSubscriptionDao()
.hasSubscriptionsBasedOnOnBehalfServicesForTp(subscription);
// if is last subscription...
if (isLastSubscription.longValue() == 0) {
// search for the reference...
Organization sourceOrganization = subscription.getProduct()
.getTechnicalProduct().getOrganization();
Organization targetOrganization = subscription.getOrganization();
OrganizationReference reference = getOrganizationReference(
sourceOrganization, targetOrganization);
// if found remove it
if (reference != null) {
removeTemporaryOnbehalfUsers(sourceOrganization,
targetOrganization);
dataManager.remove(reference);
dataManager.flush();
return true;
}
}
return false;
}
private void removeTemporaryOnbehalfUsers(Organization sourceOrganization,
Organization targetOrganization) {
for (PlatformUser onbehalfUser : sourceOrganization
.getOnBehalfUsersFor(targetOrganization)) {
removeActiveSessionsForOnbehalfUser(onbehalfUser);
OnBehalfUserReference master = onbehalfUser.getMaster();
onbehalfUser.getOrganization().getPlatformUsers()
.remove(onbehalfUser);
dataManager.remove(master);
}
}
private void removeActiveSessionsForOnbehalfUser(PlatformUser onbehalfUser) {
List<Session> sessions = getSessionDao().getActiveSessionsForUser(
onbehalfUser);
for (Session s : sessions) {
dataManager.remove(s);
}
}
private void sendConfirmDeactivationEmail(boolean removed,
final String oldSubscriptionId, final Subscription subscription) {
EmailType emailType = removed ? EmailType.SUBSCRIPTION_DELETED_ON_BEHALF_ACTING
: EmailType.SUBSCRIPTION_DELETED;
Marketplace marketplace = subscription.getMarketplace();
List<PlatformUser> users = manageBean
.getCustomerAdminsAndSubscriptionOwner(subscription);
for (PlatformUser user : users) {
try {
commService.sendMail(user, emailType,
new Object[] { oldSubscriptionId }, marketplace);
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_DELETION_OF_SUBSCRIPTION_CONFIRMING_FAILED);
}
}
}
/**
* Obtains the subscription and verifies that the current settings allow a
* unsubscribe operation.
*
* @param subId
* The subscription id to unsubscribe from.
* @return The subscription to unsubscribe from.
* @throws SubscriptionStateException
* Thrown in case the operation cannot be performed due to the
* current state of the subscription.
* @throws SubscriptionStillActiveException
* Thrown in case the subscription is still active.
* @throws ObjectNotFoundException
* Thrown in case the subscription cannot be found.
*/
private Subscription validateSubsciptionForUnsubscribe(String subId)
throws SubscriptionStateException,
SubscriptionStillActiveException, ObjectNotFoundException {
Subscription subscription = manageBean.loadSubscription(subId, 0);
stateValidator.checkUnsubscribingAllowed(subscription);
// Check whether there are active sessions
List<Session> activeSessions = prodSessionMgmt
.getProductSessionsForSubscriptionTKey(subscription.getKey());
if (activeSessions.size() > 0) {
// there are still active sessions, so deletion must
// fail: throw exception
sessionCtx.setRollbackOnly();
SubscriptionStillActiveException ssa = new SubscriptionStillActiveException(
"There are still "
+ activeSessions.size()
+ " sessions active for the subscription with key '"
+ subscription.getKey() + "'",
SubscriptionStillActiveException.Reason.ACTIVE_SESSIONS);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, ssa,
LogMessageIdentifier.WARN_SUBSCRIPTION_DELETION_FAILED);
throw ssa;
}
return subscription;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public Subscription loadSubscription(long subscriptionKey)
throws ObjectNotFoundException {
return dataManager.getReference(Subscription.class, subscriptionKey);
}
/**
* Check if one of the platform parameter constraints are violated.
*
* @param subscription
* the subscription
* @param currentUser
* the current user
* @throws SubscriptionMigrationException
* in case one of the platform parameters is violated
*/
private void checkPlatformParameterConstraints(Subscription subscription,
Product targetProduct, PlatformUser currentUser)
throws SubscriptionMigrationException {
ParameterSet paramSet = targetProduct.getParameterSet();
if (paramSet == null || paramSet.getParameters() == null
|| paramSet.getParameters().isEmpty()) {
return;
}
for (Parameter param : paramSet.getParameters()) {
ParameterDefinition def = param.getParameterDefinition();
if (def.getParameterType() == ParameterType.PLATFORM_PARAMETER
&& param.getValue() != null) {
String subscriptionId = subscription.getSubscriptionId();
if (PlatformParameterIdentifiers.NAMED_USER.equals(def
.getParameterId())) {
int current = subscription.getUsageLicenses().size();
long max = param.getLongValue();
if (current > max) {
sessionCtx.setRollbackOnly();
SubscriptionMigrationException e = new SubscriptionMigrationException(
"Parameter check failed",
Reason.PARAMETER_USERS, new Object[] {
subscriptionId,
String.valueOf(current),
String.valueOf(max) });
LOG.logError(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.ERROR_MIGRATE_SUBSCRIPTION_AS_CHECK_PARAMETER,
Long.toString(currentUser.getKey()), Long
.toString(subscription.getKey()), Long
.toString(subscription
.getOrganizationKey()), def
.getParameterId());
throw e;
}
} else if (PlatformParameterIdentifiers.PERIOD.equals(def
.getParameterId())) {
long usedTime = DateFactory.getInstance()
.getTransactionTime()
- subscription.getActivationDate().longValue();
if (usedTime > param.getLongValue()) {
sessionCtx.setRollbackOnly();
SubscriptionMigrationException e = new SubscriptionMigrationException(
"Parameter check failed",
Reason.PARAMETER_PERIOD,
new Object[] { subscriptionId });
LOG.logError(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.ERROR_MIGRATE_SUBSCRIPTION_AS_CHECK_PARAMETER,
Long.toString(currentUser.getKey()), Long
.toString(subscription.getKey()), Long
.toString(subscription
.getOrganizationKey()), def
.getParameterId());
throw e;
}
}
}
}
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public List<VOService> getUpgradeOptions(String subscriptionId)
throws ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
Subscription subscription = manageBean.checkSubscriptionOwner(
subscriptionId, 0);
return getUpgradeOptions(subscription);
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public List<VOService> getUpgradeOptions(long subscriptionKey)
throws ObjectNotFoundException, OperationNotPermittedException {
Subscription subscription = manageBean.checkSubscriptionOwner(null,
subscriptionKey);
return getUpgradeOptions(subscription);
}
private List<VOService> getUpgradeOptions(Subscription subscription)
throws OperationNotPermittedException {
// 1. retrieve the related product
Organization organization = dataManager.getCurrentUser()
.getOrganization();
PermissionCheck.owns(subscription, organization, LOG);
Product product = subscription.getProduct();
// 2. retrieve and return the compatible products
List<Product> compatibleProducts = product.getCompatibleProductsList();
// 3. get customer specific products
long supplierKey = product.getVendor().getKey();
compatibleProducts = replaceByCustomerSpecificProducts(
compatibleProducts, supplierKey, organization);
List<VOService> result = new ArrayList<>(compatibleProducts.size());
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
for (Product prod : compatibleProducts) {
result.add(ProductAssembler.toVOProduct(prod, facade));
}
return result;
}
/**
* Replaces global products by customer specific products based on the
* global ones if existing. Global and specific products that are not active
* will be removed.
*
* @param products
* the products to get customer specific ones for
* @param supplierKey
* the supplier key identifying the owner of the products
* @param organization
* the customer organization to get customer specific products
* for
* @return the list containing the customer specific products and the global
* ones not having customer specific versions
*/
List<Product> replaceByCustomerSpecificProducts(List<Product> products,
long supplierKey, Organization organization) {
// read customer specific products
List<Product> customerProducts = getProductDao()
.getProductForCustomerOnly(supplierKey, organization);
// replace products by customer specific products if existent
Map<Long, Product> keyToProduct = new HashMap<>();
for (Product prod : customerProducts) {
keyToProduct.put(Long.valueOf(prod.getTemplate().getKey()), prod);
}
List<Product> temp = new ArrayList<>(products.size());
for (Product prod : products) {
Long key = Long.valueOf(prod.getKey());
if (keyToProduct.containsKey(key)) {
Product custSpec = keyToProduct.get(key);
if (custSpec.getStatus() == ServiceStatus.ACTIVE) {
temp.add(custSpec);
}
} else if (prod.getStatus() == ServiceStatus.ACTIVE) {
temp.add(prod);
}
}
return temp;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public VOSubscription upgradeSubscription(VOSubscription subscription,
VOService service, VOPaymentInfo paymentInfo,
VOBillingContact billingContact, List<VOUda> udas)
throws ObjectNotFoundException, OperationNotPermittedException,
SubscriptionMigrationException, PaymentInformationException,
SubscriptionStateException, ServiceChangedException,
PriceModelException, ConcurrentModificationException,
TechnicalServiceNotAliveException, OperationPendingException,
MandatoryUdaMissingException, NonUniqueBusinessKeyException,
ValidationException {
ArgumentValidator.notNull("subscription", subscription);
ArgumentValidator.notNull("service", service);
manageBean.checkSubscriptionOwner(subscription.getSubscriptionId(),
subscription.getKey());
validateSettingsForUpgrading(subscription, service, paymentInfo,
billingContact);
validateTriggerProcessForUpgradeSubscription(subscription);
TriggerProcess triggerProcess = createTriggerProcessForUpgradeSubscription(
subscription, service, paymentInfo, billingContact, udas);
TriggerDefinition triggerDefinition = triggerProcess
.getTriggerDefinition();
Subscription upgradedSub = null;
if (triggerDefinition == null) {
try {
upgradedSub = upgradeSubscriptionInt(triggerProcess);
} catch (ObjectNotFoundException | SubscriptionStateException
| OperationNotPermittedException | ServiceChangedException
| PriceModelException | PaymentInformationException
| SubscriptionMigrationException
| ConcurrentModificationException
| TechnicalServiceNotAliveException
| MandatoryUdaMissingException
| NonUniqueBusinessKeyException | ValidationException e) {
sessionCtx.setRollbackOnly();
throw e;
}
} else if (triggerDefinition.isSuspendProcess()) {
triggerProcess
.setTriggerProcessIdentifiers(TriggerProcessIdentifiers
.createUpgradeSubscription(dataManager,
TriggerType.UPGRADE_SUBSCRIPTION,
subscription));
dataManager.merge(triggerProcess);
}
return SubscriptionAssembler.toVOSubscription(upgradedSub,
new LocalizerFacade(localizer, dataManager.getCurrentUser()
.getLocale()));
}
private TriggerProcess createTriggerProcessForUpgradeSubscription(
VOSubscription subscription, VOService service,
VOPaymentInfo paymentInfo, VOBillingContact billingContact,
List<VOUda> udas) {
TriggerMessage message = new TriggerMessage(
TriggerType.UPGRADE_SUBSCRIPTION);
List<TriggerProcessMessageData> list = triggerQS
.sendSuspendingMessages(Collections.singletonList(message));
TriggerProcess triggerProcess = list.get(0).getTrigger();
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.OBJECT_ID,
subscription.getSubscriptionId());
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscription);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.PRODUCT, service);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.PAYMENTINFO, paymentInfo);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.BILLING_CONTACT, billingContact);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.UDAS, udas);
return triggerProcess;
}
private void validateTriggerProcessForUpgradeSubscription(
VOSubscription subscription) throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
if (validator.isModifyOrUpgradeSubscriptionPending(subscription)) {
String subID = subscription.getSubscriptionId();
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to upgrade or modify the subscription with ID '%s'",
subID), ReasonEnum.UPGRADE_SUBSCRIPTION,
new Object[] { subID });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_UPGRADE_SUBSCRIPTION_FAILED_DUE_TO_TRIGGER_CONFLICT,
subID);
throw ope;
}
}
private void validateTriggerProcessForUpgradeSubscriptionBySubscriptionKey(
long subscriptionKey, String subscriptionID)
throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
if (validator.isUpgradeSubscriptionPending(subscriptionKey)) {
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to upgrade or modify the subscription with ID '%s'",
subscriptionID), ReasonEnum.UPGRADE_SUBSCRIPTION,
new Object[] { subscriptionID });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_ADD_REVOKE_USER_FAILED_DUE_TO_TRIGGER_CONFLICT,
subscriptionID);
throw ope;
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public Subscription upgradeSubscriptionInt(TriggerProcess tp)
throws ObjectNotFoundException, SubscriptionStateException,
OperationNotPermittedException, ServiceChangedException,
PriceModelException, PaymentInformationException,
SubscriptionMigrationException, ConcurrentModificationException,
TechnicalServiceNotAliveException, NonUniqueBusinessKeyException,
ValidationException, MandatoryUdaMissingException {
VOSubscription current = tp.getParamValueForName(
TriggerProcessParameterName.SUBSCRIPTION).getValue(
VOSubscription.class);
VOService voTargetProduct = tp.getParamValueForName(
TriggerProcessParameterName.PRODUCT).getValue(VOService.class);
VOPaymentInfo voPaymentInfo = tp.getParamValueForName(
TriggerProcessParameterName.PAYMENTINFO).getValue(
VOPaymentInfo.class);
VOBillingContact voBillingContact = tp.getParamValueForName(
TriggerProcessParameterName.BILLING_CONTACT).getValue(
VOBillingContact.class);
List<VOUda> udas = ParameterizedTypes.list(
tp.getParamValueForName(TriggerProcessParameterName.UDAS)
.getValue(List.class), VOUda.class);
Product dbTargetProduct = dataManager.getReference(Product.class,
voTargetProduct.getKey());
Subscription dbSubscription = dataManager.getReference(
Subscription.class, current.getKey());
PlatformUser currentUser = dataManager.getCurrentUser();
Subscription subscription = manageBean.loadSubscription(
current.getSubscriptionId(), 0);
BaseAssembler.verifyVersionAndKey(subscription, current);
Product initialProduct = subscription.getProduct();
PaymentInfo initialPaymentInfo = subscription.getPaymentInfo();
BillingContact initialBillingContact = subscription.getBillingContact();
validateSettingsForUpgrading(current, voTargetProduct, voPaymentInfo,
voBillingContact);
// validates parameter version and parameter values
checkIfParametersAreModified(subscription, dbSubscription,
initialProduct, dbTargetProduct,
voTargetProduct.getParameters(), true);
PaymentInfo paymentInfo = null;
BillingContact bc = null;
if (voPaymentInfo != null) {
// Valid payment information have been passed -> use it for the
// upgraded subscription
paymentInfo = dataManager.getReference(PaymentInfo.class,
voPaymentInfo.getKey());
}
if (voBillingContact != null) {
bc = dataManager.getReference(BillingContact.class,
voBillingContact.getKey());
}
// log payment info before subscription changed!
audit.editPaymentType(dataManager, subscription, paymentInfo);
// log billing address before subscription changed!
audit.editBillingAddress(dataManager, subscription, bc);
// update subscription
subscription.setPaymentInfo(paymentInfo);
subscription.setBillingContact(bc);
// product and parameters are copied
copyProductAndModifyParametersForUpgrade(subscription, dbTargetProduct,
currentUser, voTargetProduct.getParameters());
List<Uda> existingUdas = manageBean.getExistingUdas(subscription);
List<VOUda> updatedList = getUpdatedSubscriptionAttributes(udas,
existingUdas);
logSubscriptionAttributeForEdit(subscription, updatedList);
if (dbTargetProduct.getTechnicalProduct().getProvisioningType()
.equals(ProvisioningType.SYNCHRONOUS)) {
// bugfix 8068
String oldServiceId = initialProduct.getTemplate() != null ? initialProduct
.getTemplate().getProductId() : initialProduct
.getProductId();
String newServiceId = dbTargetProduct.getTemplate() != null ? dbTargetProduct
.getTemplate().getProductId() : dbTargetProduct
.getProductId();
// remove old product
dataManager.remove(initialProduct);
saveUdasForSubscription(udas, subscription);
// finally send confirmation mail to the organization admin
modUpgBean.sendConfirmUpgradationEmail(subscription, oldServiceId,
newServiceId);
} else if (dbTargetProduct.getTechnicalProduct().getProvisioningType()
.equals(ProvisioningType.ASYNCHRONOUS)) {
long subscriptionKey = subscription.getKey();
if (paymentInfo != null) {
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_PAYMENTINFO,
String.valueOf(paymentInfo.getKey()));
}
if (bc != null) {
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_BILLINGCONTACT,
String.valueOf(bc.getKey()));
}
subscription.setPaymentInfo(initialPaymentInfo);
subscription.setBillingContact(initialBillingContact);
saveUdasForAsyncModifyOrUpgradeSubscription(udas, dbSubscription);
}
dataManager.flush();
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.UPGRADE_SUBSCRIPTION, tp
.getTriggerProcessParameters(), dataManager
.getCurrentUser().getOrganization()));
// log upDowngrade subscription
audit.upDowngradeSubscription(dataManager, subscription,
initialProduct, dbTargetProduct);
return subscription;
}
/**
* Validates the data of the specified subscription and target product to
* evaluate if the upgrade is possible.
*
* @param current
* The current subscription.
* @param newProduct
* The product to migrate to.
* @param voBillingContact
* @throws ObjectNotFoundException
* Thrown in case the subscription or target product cannot be
* found.
* @throws SubscriptionStateException
* Thrown in case the subscription state does not allow a
* migration.
* @throws OperationNotPermittedException
* Thrown in case the caller tries to modify another
* organization's object.
* @throws ServiceChangedException
* Thrown in case the target product definition has been
* modified in the meantime.
* @throws PriceModelException
* Thrown in case the target product is missing a price model.
* @throws PaymentInformationException
* Thrown in case the calling organization does not have a
* payment record.
* @throws SubscriptionMigrationException
* Thrown in case the migration is not possible as the products
* are not compatible.
*/
void validateSettingsForUpgrading(VOSubscription current,
VOService newProduct, VOPaymentInfo paymentInfo,
VOBillingContact voBillingContact) throws ObjectNotFoundException,
SubscriptionStateException, OperationNotPermittedException,
ServiceChangedException, PriceModelException,
PaymentInformationException, SubscriptionMigrationException {
// 1. retrieve the subscription details and the target product
Subscription subscription = manageBean.loadSubscription(
current.getSubscriptionId(), 0);
stateValidator.checkModifyAllowedForUpgrading(subscription);
PlatformUser currentUser = dataManager.getCurrentUser();
Organization organization = currentUser.getOrganization();
PermissionCheck.owns(subscription, organization, LOG);
Product currentProduct = subscription.getProduct();
Product targetProduct = dataManager.getReference(Product.class,
newProduct.getKey());
// check if the product has been changed in the meantime or it
// is inactive....
checkIfProductIsUptodate(targetProduct, newProduct);
// 2. check if the payment information parameter is set correctly
PriceModel targetPriceModel = targetProduct.getPriceModel();
if (targetPriceModel == null) {
PriceModelException mpme = new PriceModelException(
PriceModelException.Reason.NOT_DEFINED);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, mpme,
LogMessageIdentifier.WARN_MIGRATE_PRODUCT_FAILED,
Long.toString(targetProduct.getKey()));
throw mpme;
}
if (targetPriceModel.isChargeable()) {
PaymentDataValidator.validateNotNull(paymentInfo, voBillingContact);
PaymentInfo pi = dataManager.getReference(PaymentInfo.class,
paymentInfo.getKey());
BillingContact bc = dataManager.getReference(BillingContact.class,
voBillingContact.getKey());
PermissionCheck.owns(pi, organization, LOG);
PermissionCheck.owns(bc, organization, LOG);
PaymentDataValidator.validatePaymentTypeSupportedBySupplier(
organization, targetProduct, pi.getPaymentType());
PaymentDataValidator.validatePaymentInfoDataForUsage(pi);
}
// 3. now check if the new product is really compatible to the
// current one
List<Product> compatibleProducts = currentProduct
.getCompatibleProductsList();
// we won't find products in this list that are not active
compatibleProducts = replaceByCustomerSpecificProducts(
compatibleProducts, currentProduct.getVendorKey(), organization);
boolean isCompatibleProduct = false;
for (Product compatibleProduct : compatibleProducts) {
if (compatibleProduct.getKey() == targetProduct.getKey()) {
isCompatibleProduct = true;
}
}
if (!isCompatibleProduct) {
sessionCtx.setRollbackOnly();
SubscriptionMigrationException smf = new SubscriptionMigrationException(
"Migration of subscription failed",
Reason.INCOMPATIBLE_SERVICES, new Object[] {
subscription.getSubscriptionId(),
targetProduct.getCleanProductId() });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
smf,
LogMessageIdentifier.WARN_MIGRATE_PRODUCT_FAILED_NOT_COMPATIBLE,
Long.toString(currentUser.getKey()),
Long.toString(subscription.getKey()),
Long.toString(subscription.getOrganizationKey()),
Long.toString(targetProduct.getKey()),
Long.toString(subscription.getProduct().getKey()));
throw smf;
}
}
/**
* Copies the product and modifies the given parameters. Also informs the
* technical service about the changed parameter set.
*
* @param subscription
* the subscription to create a copy of the product for
* @param targetProduct
* the product to copy
* @param currentUser
* the currently logged in user
* @param voTargetParameters
* the list of modified or configurable parameters
* @throws SubscriptionMigrationException
* @throws TechnicalServiceNotAliveException
* Thrown in case the service for the operation cannot be
* reached.
*/
void copyProductAndModifyParametersForUpdate(Subscription subscription,
Product targetProduct, PlatformUser currentUser,
List<VOParameter> voTargetParameters)
throws SubscriptionMigrationException,
TechnicalServiceNotAliveException {
Product targetProductCopy = null;
ProvisioningType provisioningType = targetProduct.getTechnicalProduct()
.getProvisioningType();
if (provisioningType.equals(ProvisioningType.SYNCHRONOUS)) {
targetProductCopy = targetProduct;
} else if (provisioningType.equals(ProvisioningType.ASYNCHRONOUS)) {
targetProductCopy = copyProductForSubscription(targetProduct,
subscription, true);
}
List<Parameter> modifiedParametersForLog = updateConfiguredParameterValues(
targetProductCopy, voTargetParameters, subscription);
// verify the platform parameter and send the new parameter to the
// technical product
checkPlatformParameterConstraints(subscription, targetProductCopy,
currentUser);
try {
if (provisioningType.equals(ProvisioningType.ASYNCHRONOUS)) {
subscription.setAsyncTempProduct(targetProductCopy);
handleAsyncUpdateSubscription(subscription, targetProductCopy);
} else if (provisioningType.equals(ProvisioningType.SYNCHRONOUS)) {
// BUG 9998. It has to be ensured, that no call on pending
// subscription
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
appManager.modifySubscription(subscription);
}
}
} catch (TechnicalServiceNotAliveException e) {
sessionCtx.setRollbackOnly();
throw e;
} catch (TechnicalServiceOperationException e1) {
sessionCtx.setRollbackOnly();
Object[] params;
String subscriptionId = subscription.getSubscriptionId();
if (e1.getMessageParams() != null
&& e1.getMessageParams().length > 1) {
params = new Object[] { subscriptionId, e1.getMessage(),
e1.getMessageParams()[1] };
} else {
params = new Object[] { subscriptionId, e1.getMessage(), "" };
}
SubscriptionMigrationException smf = new SubscriptionMigrationException(
"Modify ParameterSet failed", Reason.PARAMETER, params);
LOG.logError(Log4jLogger.SYSTEM_LOG, smf,
LogMessageIdentifier.ERROR_MODIFY_PARAMETER_SET_FAILED);
throw smf;
}
audit.editSubscriptionParameterConfiguration(dataManager,
targetProductCopy, modifiedParametersForLog);
}
/**
* Copies the product and modifies the given parameters. Also informs the
* technical service about the changed parameter set.
*
* @param subscription
* the subscription to create a copy of the product for
* @param targetProduct
* the product to copy
* @param currentUser
* the currently logged in user
* @param voTargetParameters
* the list of modified or configurable parameters
* @throws SubscriptionMigrationException
* @throws TechnicalServiceNotAliveException
* Thrown in case the service for the operation cannot be
* reached.
* @throws ObjectNotFoundException
*/
void copyProductAndModifyParametersForUpgrade(Subscription subscription,
Product targetProduct, PlatformUser currentUser,
List<VOParameter> voTargetParameters)
throws SubscriptionMigrationException,
TechnicalServiceNotAliveException, ObjectNotFoundException {
ProvisioningType provisioningType = targetProduct.getTechnicalProduct()
.getProvisioningType();
Product targetProductCopy = copyProductForSubscription(targetProduct,
subscription, false);
List<Parameter> modifiedParametersForLog = updateConfiguredParameterValues(
targetProductCopy, voTargetParameters, subscription);
// verify the platform parameter
checkPlatformParameterConstraints(subscription, targetProductCopy,
currentUser);
try {
if (provisioningType.equals(ProvisioningType.ASYNCHRONOUS)) {
subscription.setAsyncTempProduct(targetProductCopy);
handleAsyncUpgradeSubscription(subscription, targetProductCopy);
} else if (provisioningType.equals(ProvisioningType.SYNCHRONOUS)) {
targetProductCopy.getPriceModel()
.setProvisioningCompleted(true);
subscription.bindToProduct(targetProductCopy);
// BE08022: Activate the subscription if it is up-/downgraded
if (isActivationAllowed(subscription, true)) {
appManager.activateInstance(subscription);
subscription.setStatus(SubscriptionStatus.ACTIVE);
}
// BUG 9998. It has to be ensured, that no call on pending
// subscription
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
appManager.upgradeSubscription(subscription);
}
}
} catch (TechnicalServiceNotAliveException e) {
sessionCtx.setRollbackOnly();
throw e;
} catch (TechnicalServiceOperationException e1) {
sessionCtx.setRollbackOnly();
Object[] params;
String subscriptionId = subscription.getSubscriptionId();
if (e1.getMessageParams() != null
&& e1.getMessageParams().length > 1) {
params = new Object[] { subscriptionId, e1.getMessage(),
e1.getMessageParams()[1] };
} else {
params = new Object[] { subscriptionId, e1.getMessage(), "" };
}
SubscriptionMigrationException smf = new SubscriptionMigrationException(
"Modify ParameterSet failed", Reason.PARAMETER, params);
LOG.logError(Log4jLogger.SYSTEM_LOG, smf,
LogMessageIdentifier.ERROR_MODIFY_PARAMETER_SET_FAILED);
throw smf;
}
audit.editSubscriptionParameterConfiguration(dataManager,
targetProductCopy, modifiedParametersForLog);
}
private Product copyProductForSubscription(Product targetProduct,
Subscription subscription, boolean provisiongCompleted) {
Product targetProductCopy = targetProduct.copyForSubscription(
targetProduct.getTargetCustomer(), subscription);
if (targetProductCopy.getPriceModel() != null) {
// FIXME LG clean
// For asynchronous upgrade the first target pricemodel version is
// created when subscription is still in PENDING_UPD, but must be
// fitered for billing. Set the indicating flag before persisting.
targetProductCopy.getPriceModel().setProvisioningCompleted(
provisiongCompleted);
}
try {
dataManager.persist(targetProductCopy);
} catch (NonUniqueBusinessKeyException ex) {
// this must never happen as the product copy must have unique
// id
SaaSSystemException se = new SaaSSystemException(
"The product copy method didn't create a unique productId.",
ex);
LOG.logError(
Log4jLogger.SYSTEM_LOG,
se,
LogMessageIdentifier.ERROR_CREATE_UNIQUE_PRODUCT_ID_FAILED_IN_PRODUCT_COPY);
throw se;
}
copyLocalizedPricemodelValues(targetProductCopy, targetProduct);
return targetProductCopy;
}
/**
* Sets subscription status and informs the technical service about the
* changed parameter set when asynchronously update subscription.
*
* @param subscription
* the subscription to update
* @param targetProduct
* the target product owned by the subscription
* @throws TechnicalServiceNotAliveException
* @throws TechnicalServiceOperationException
*/
void handleAsyncUpdateSubscription(Subscription subscription,
Product targetProduct) throws TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
EnumSet<SubscriptionStatus> set = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.SUSPENDED);
SubscriptionStatus status = subscription.getStatus();
if (set.contains(status)) {
appManager.asyncModifySubscription(subscription, targetProduct);
switch (status) {
case ACTIVE:
subscription.setStatus(SubscriptionStatus.PENDING_UPD);
break;
case SUSPENDED:
subscription.setStatus(SubscriptionStatus.SUSPENDED_UPD);
break;
default:
break;
}
}
}
/**
* Sets subscription status and informs the technical service about the
* changed parameter set when asynchronously upgrade subscription.
*
* @param subscription
* the subscription to update
* @param targetProduct
* the target product owned by the subscription
* @throws TechnicalServiceNotAliveException
* @throws TechnicalServiceOperationException
*/
void handleAsyncUpgradeSubscription(Subscription subscription,
Product targetProduct) throws TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
EnumSet<SubscriptionStatus> set = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.EXPIRED, SubscriptionStatus.SUSPENDED);
SubscriptionStatus status = subscription.getStatus();
if (set.contains(status)) {
appManager.asyncUpgradeSubscription(subscription, targetProduct);
switch (status) {
case ACTIVE:
subscription.setStatus(SubscriptionStatus.PENDING_UPD);
break;
case SUSPENDED:
subscription.setStatus(SubscriptionStatus.SUSPENDED_UPD);
break;
case EXPIRED:
default:
break;
}
}
}
boolean isActivationAllowed(Subscription subscription,
boolean activateExpiredSubscription) throws ObjectNotFoundException {
if (subscription == null) {
return false;
}
if (activateExpiredSubscription
&& (subscription.getStatus() == SubscriptionStatus.EXPIRED)) {
return true;
}
if (subscription.getStatus() != SubscriptionStatus.SUSPENDED) {
return false;
}
if (!subscription.getPriceModel().isChargeable()) {
return true;
}
if (subscription.getBillingContact() == null) {
return false;
}
PaymentType subPayType = null;
PaymentInfo paymentInfo = subscription.getPaymentInfo();
if (paymentInfo != null) {
subPayType = paymentInfo.getPaymentType();
}
if (subPayType == null) {
return false;
}
long serviceKey = subscription.getProduct().getKey();
boolean paymentEnabled;
paymentEnabled = accountService.isPaymentTypeEnabled(serviceKey,
subPayType.getKey());
return paymentEnabled;
}
/**
* Checks if the product read from the database is in active state and equal
* to the one passed in as voproduct comparing the versions.
*
* @param prod
* the product just read from the database
* @param voProd
* the product passed in through the interface
* @throws ServiceChangedException
* in case the product read from the database isn't active or
* version based different to the passed voproduct
*/
private void checkIfProductIsUptodate(Product prod, VOService voProd)
throws ServiceChangedException {
if (prod.getStatus() != ServiceStatus.ACTIVE) {
throw new ServiceChangedException(
ServiceChangedException.Reason.SERVICE_INACCESSIBLE);
}
if (prod.getVersion() != voProd.getVersion()) {
throw new ServiceChangedException(
ServiceChangedException.Reason.SERVICE_MODIFIED);
}
ParameterSet parameterSet = prod.getParameterSet();
if (parameterSet != null) {
List<Parameter> parameters = parameterSet.getParameters();
for (Parameter doParameter : parameters) {
for (VOParameter param : voProd.getParameters()) {
if (param.getKey() == doParameter.getKey()
&& param.getVersion() != doParameter.getVersion()) {
throw new ServiceChangedException(
ServiceChangedException.Reason.SERVICE_MODIFIED);
}
}
}
}
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public VOSubscriptionDetails modifySubscription(
VOSubscription subscription, List<VOParameter> parameters,
List<VOUda> udas) throws NonUniqueBusinessKeyException,
ObjectNotFoundException, OperationNotPermittedException,
ValidationException, SubscriptionMigrationException,
ConcurrentModificationException, TechnicalServiceNotAliveException,
OperationPendingException, MandatoryUdaMissingException,
SubscriptionStateException {
ArgumentValidator.notNull("subscription", subscription);
Subscription subFromDB = manageBean.checkSubscriptionOwner(
subscription.getSubscriptionId(), subscription.getKey());
validateSubscriptionSettings(subscription);
validateTriggerProcessForModifySubscription(subscription);
PlatformUser currentUser = dataManager.getCurrentUser();
boolean canModify = PermissionCheck
.shouldWeProceedWithUpdatingSubscription(subscription,
subFromDB, currentUser);
VOSubscriptionDetails result;
if (canModify) {
TriggerProcess triggerProcess = createTriggerProcessForModifySubscription(
subscription, parameters, udas);
result = processTriggerProcessForSubscriptionModification(
subscription, triggerProcess);
} else {
LocalizerFacade facade = new LocalizerFacade(localizer,
currentUser.getLocale());
result = SubscriptionAssembler.toVOSubscriptionDetails(subFromDB,
facade);
}
return result;
}
private VOSubscriptionDetails processTriggerProcessForSubscriptionModification(
VOSubscription subscription, TriggerProcess triggerProcess)
throws ObjectNotFoundException, NonUniqueBusinessKeyException,
ValidationException, OperationNotPermittedException,
SubscriptionMigrationException, ConcurrentModificationException,
TechnicalServiceNotAliveException, MandatoryUdaMissingException,
SubscriptionStateException {
VOSubscriptionDetails result = null;
TriggerDefinition triggerDefinition = triggerProcess
.getTriggerDefinition();
if (triggerDefinition == null) {
try {
result = modifySubscriptionInt(triggerProcess);
} catch (ObjectNotFoundException | NonUniqueBusinessKeyException
| OperationNotPermittedException
| SubscriptionMigrationException
| ConcurrentModificationException
| TechnicalServiceNotAliveException | ValidationException
| MandatoryUdaMissingException | SubscriptionStateException e) {
sessionCtx.setRollbackOnly();
throw e;
}
} else if (triggerDefinition.isSuspendProcess()) {
triggerProcess
.setTriggerProcessIdentifiers(TriggerProcessIdentifiers
.createUpgradeSubscription(dataManager,
TriggerType.MODIFY_SUBSCRIPTION,
subscription));
dataManager.merge(triggerProcess);
}
return result;
}
private TriggerProcess createTriggerProcessForModifySubscription(
VOSubscription subscription, List<VOParameter> parameters,
List<VOUda> udas) {
TriggerMessage message = new TriggerMessage(
TriggerType.MODIFY_SUBSCRIPTION);
List<TriggerProcessMessageData> list = triggerQS
.sendSuspendingMessages(Collections.singletonList(message));
TriggerProcess triggerProcess = list.get(0).getTrigger();
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.OBJECT_ID,
subscription.getSubscriptionId());
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.SUBSCRIPTION, subscription);
List<VOParameter> params = parameters;
if (params == null) {
params = new ArrayList<>();
}
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.PARAMETERS, params);
triggerProcess.addTriggerProcessParameter(
TriggerProcessParameterName.UDAS, udas);
return triggerProcess;
}
private void validateTriggerProcessForModifySubscription(
VOSubscription subscription) throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
String subID = subscription.getSubscriptionId();
if (validator.isModifyOrUpgradeSubscriptionPending(subscription)) {
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to modify or upgrade the subscription with key '%s'",
subID), ReasonEnum.MODIFY_SUBSCRIPTION,
new Object[] { subID });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_MODIFY_SUBSCRIPTION_FAILED_DUE_TO_TRIGGER_CONFLICT,
subID);
throw ope;
}
}
private void validateTriggerProcessForModifySubscriptionBySubscriptionKey(
long subscriptionKey, String subscriptionID)
throws OperationPendingException {
TriggerProcessValidator validator = new TriggerProcessValidator(
dataManager);
if (validator.isModifySubscriptionPending(subscriptionKey)) {
OperationPendingException ope = new OperationPendingException(
String.format(
"Operation cannot be performed. There is already another pending request to modify or upgrade the subscription with key '%s'",
subscriptionID), ReasonEnum.MODIFY_SUBSCRIPTION,
new Object[] { subscriptionID });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
ope,
LogMessageIdentifier.WARN_ADD_REVOKE_USER_FAILED_DUE_TO_TRIGGER_CONFLICT,
subscriptionID);
throw ope;
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public VOSubscriptionDetails modifySubscriptionInt(TriggerProcess tp)
throws ObjectNotFoundException, NonUniqueBusinessKeyException,
ValidationException, OperationNotPermittedException,
SubscriptionMigrationException, ConcurrentModificationException,
TechnicalServiceNotAliveException, MandatoryUdaMissingException,
SubscriptionStateException {
VOSubscription subscription = tp.getParamValueForName(
TriggerProcessParameterName.SUBSCRIPTION).getValue(
VOSubscription.class);
List<VOParameter> modifiedParameters = ParameterizedTypes.list(tp
.getParamValueForName(TriggerProcessParameterName.PARAMETERS)
.getValue(List.class), VOParameter.class);
List<VOUda> udas = ParameterizedTypes.list(
tp.getParamValueForName(TriggerProcessParameterName.UDAS)
.getValue(List.class), VOUda.class);
Subscription dbSubscription = validateSubscriptionSettings(subscription);
final PlatformUser currentUser = dataManager.getCurrentUser();
Organization organization = currentUser.getOrganization();
UserGroup unit = getUnit(subscription.getUnitKey(),
subscription.getUnitName(), organization.getKey());
stateValidator.checkModifyAllowedForUpdating(dbSubscription);
// get initial values of subscription
String dbSubscriptionId = dbSubscription.getSubscriptionId();
boolean subIdChanged = !dbSubscriptionId.equals(subscription
.getSubscriptionId());
PlatformUser dbOwner = dbSubscription.getOwner();
Product dbProduct = dbSubscription.getProduct();
String dbPurchaseNumber = dbSubscription.getPurchaseOrderNumber();
UserGroup dbUnit = dbSubscription.getUserGroup();
// set new values for subscription
dbSubscription.setSubscriptionId(subscription.getSubscriptionId());
dbSubscription.setPurchaseOrderNumber(subscription
.getPurchaseOrderNumber());
if (currentUser.isOrganizationAdmin() || currentUser.isUnitAdmin()) {
dbSubscription.setUserGroup(unit);
}
manageBean.setSubscriptionOwner(dbSubscription,
subscription.getOwnerId(), true);
boolean backupOldValues = handleParameterModifications(
modifiedParameters, dbSubscription, currentUser, subIdChanged,
dbProduct);
List<Uda> existingUdas = manageBean.getExistingUdas(dbSubscription);
List<VOUda> updatedUdas = getUpdatedSubscriptionAttributes(udas,
existingUdas);
logSubscriptionAttributeForEdit(dbSubscription, updatedUdas);
logSubscriptionOwner(dbSubscription, dbOwner);
if (backupOldValues) {
long subscriptionKey = dbSubscription.getKey();
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_SUBSCRIPTIONID,
subscription.getSubscriptionId());
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_ORGANIZATIONID,
dbSubscription.getOrganization().getOrganizationId());
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_PURCHASEORDERNUMBER,
subscription.getPurchaseOrderNumber());
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_OWNERID,
subscription.getOwnerId());
modUpgBean.storeModifiedEntity(subscriptionKey,
ModifiedEntityType.SUBSCRIPTION_UNIT,
String.valueOf(subscription.getUnitKey()));
// set initial values again
dbSubscription.setSubscriptionId(dbSubscriptionId);
dbSubscription.setPurchaseOrderNumber(dbPurchaseNumber);
String dbOwnerId = dbOwner == null ? null : dbOwner.getUserId();
manageBean.setSubscriptionOwner(dbSubscription, dbOwnerId, true);
dbSubscription.setUserGroup(dbUnit);
saveUdasForAsyncModifyOrUpgradeSubscription(udas, dbSubscription);
} else {
saveUdasForSubscription(udas, dbSubscription);
}
dataManager.flush();
LocalizerFacade facade = new LocalizerFacade(localizer,
currentUser.getLocale());
VOSubscriptionDetails result = SubscriptionAssembler
.toVOSubscriptionDetails(dbSubscription, facade);
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.MODIFY_SUBSCRIPTION, tp
.getTriggerProcessParameters(), dataManager
.getCurrentUser().getOrganization()));
triggerQS.sendAllNonSuspendingMessages(TriggerMessage.create(
TriggerType.SUBSCRIPTION_MODIFICATION, tp
.getTriggerProcessParameters(), dbSubscription
.getProduct().getVendor()));
return result;
}
private boolean handleParameterModifications(
List<VOParameter> modifiedParameters, Subscription dbSubscription,
final PlatformUser currentUser, boolean subIdChanged,
Product dbProduct) throws SubscriptionMigrationException,
ConcurrentModificationException, ValidationException,
TechnicalServiceNotAliveException {
try {
if (subIdChanged
|| checkIfParametersAreModified(dbSubscription,
dbSubscription, dbProduct, dbProduct,
modifiedParameters, false)) {
copyProductAndModifyParametersForUpdate(dbSubscription,
dbProduct, currentUser, modifiedParameters);
if (dbProduct.getTechnicalProduct().getProvisioningType()
.equals(ProvisioningType.ASYNCHRONOUS)) {
return true;
}
}
} catch (ServiceChangedException e) {
throw new ConcurrentModificationException(e.getMessage());
}
return false;
}
/**
* Validates the settings of the specified subscription object.
*
* @param subscription
* The subscription to be validated.
* @return The domain object representation of the subscription to be
* modified.
* @throws ValidationException
* Thrown in case the settings could not be validated.
* @throws ObjectNotFoundException
* Thrown in case the subscription could not be found.
* @throws OperationNotPermittedException
* Thrown in case the caller tries to modify another
* organization's object.
* @throws NonUniqueBusinessKeyException
* Thrown in case there already is a subscription with the given
* id for the current organization (only checked in caes of
* changing the current id).
* @throws ConcurrentModificationException
*/
private Subscription validateSubscriptionSettings(
VOSubscription subscription) throws ValidationException,
ObjectNotFoundException, OperationNotPermittedException,
NonUniqueBusinessKeyException, ConcurrentModificationException {
subscription.setSubscriptionId(BaseAssembler.trim(subscription
.getSubscriptionId()));
String subscriptionId = subscription.getSubscriptionId();
BLValidator.isId("subscriptionId", subscriptionId, true);
BLValidator.isDescription("purchaseOrderNumber",
subscription.getPurchaseOrderNumber(), false);
Subscription subscriptionToModify = dataManager.getReference(
Subscription.class, subscription.getKey());
PermissionCheck.owns(subscriptionToModify, dataManager.getCurrentUser()
.getOrganization(), LOG);
BaseAssembler.verifyVersionAndKey(subscriptionToModify, subscription);
String ownerId = subscription.getOwnerId();
if (ownerId != null && ownerId.length() != 0) {
checkRolesForSubscriptionOwner(ownerId);
}
if (!subscriptionToModify.getSubscriptionId().equals(subscriptionId)) {
Subscription sub = new Subscription();
sub.setOrganization(subscriptionToModify.getOrganization());
sub.setSubscriptionId(subscriptionId);
dataManager.validateBusinessKeyUniqueness(sub);
// Validate unique subscirptionId and organization in temporary
// table
Long result = getModifiedEntityDao()
.countSubscriptionOfOrganizationAndSubscription(
subscriptionToModify, subscriptionId);
if (result.longValue() > 0) {
NonUniqueBusinessKeyException ex = new NonUniqueBusinessKeyException();
LOG.logError(
Log4jLogger.SYSTEM_LOG,
ex,
LogMessageIdentifier.ERROR_SUBSCRIPTIONID_ALREADY_EXIST_IN_MODIFIEDENTITY,
subscriptionId, subscriptionToModify.getOrganization()
.getOrganizationId());
throw ex;
}
}
return subscriptionToModify;
}
void checkRolesForSubscriptionOwner(String ownerId)
throws ObjectNotFoundException, OperationNotPermittedException {
PlatformUser owner = idManager.getPlatformUser(ownerId, true);
if (!owner.hasSubscriptionOwnerRole()) {
String rolesString = UserRoleType.ORGANIZATION_ADMIN + ", "
+ UserRoleType.SUBSCRIPTION_MANAGER;
String message = "Add subscription owner failed. User '%s' does not have required roles: %s";
OperationNotPermittedException onp = new OperationNotPermittedException(
String.format(message, ownerId, rolesString));
LOG.logWarn(Log4jLogger.SYSTEM_LOG, onp,
LogMessageIdentifier.WARN_ADD_SUBSCRIPTION_OWNER_FAILED,
ownerId, rolesString);
throw onp;
}
}
/**
* To avoid unneeded migrations, check if parameters really have changed and
* if they can be changed
*
* @param dbSourceProduct
* the current product
* @param voTargetParameters
* the parameters to modify
* @return <code>true</code> if at least one parameter will be changed.
* @throws ConcurrentModificationException
* @throws ValidationException
*/
boolean checkIfParametersAreModified(Subscription subscription,
Subscription dbSubscription, Product dbSourceProduct,
Product dbTargetProduct, List<VOParameter> voTargetParameters,
boolean upgrade) throws SubscriptionMigrationException,
ServiceChangedException, ConcurrentModificationException,
ValidationException {
boolean result = false;
verifyIfParameterConcurrentlyChanged(dbTargetProduct,
voTargetParameters, upgrade);
// load db target product parameter and cache the values for better
// performance in a map
Map<String, Parameter> dbTargetParameterMap = new HashMap<>();
if (dbTargetProduct.getParameterSet() != null) {
for (Parameter dbTargetParameter : dbTargetProduct
.getParameterSet().getParameters()) {
dbTargetParameterMap.put(dbTargetParameter
.getParameterDefinition().getParameterId(),
dbTargetParameter);
}
}
Map<String, Parameter> dbSubscriptionParameterMap = new HashMap<>();
if (dbSubscription.getParameterSet() != null) {
for (Parameter dbSubParameter : dbSubscription.getParameterSet()
.getParameters()) {
dbSubscriptionParameterMap.put(dbSubParameter
.getParameterDefinition().getParameterId(),
dbSubParameter);
}
}
for (VOParameter voTargetParameter : voTargetParameters) {
String dbParameterId = voTargetParameter.getParameterDefinition()
.getParameterId();
if (dbSubscriptionParameterMap.containsKey(dbParameterId)) {
Parameter dbTargetParameter = dbTargetParameterMap
.get(dbParameterId);
Parameter dbSubscriptionParameter = dbSubscriptionParameterMap
.get(dbParameterId);
if (!upgrade
&& voTargetParameter.getParameterDefinition()
.getModificationType()
.equals(ParameterModificationType.ONE_TIME)) {
if (!compareParameterValue(dbTargetParameter,
dbSubscriptionParameter)) {
throw new ValidationException(
ValidationException.ReasonEnum.ONE_TIME_PARAMETER_NOT_ALLOWED,
null, new Object[] { dbTargetParameter
.getParameterDefinition()
.getParameterId() });
}
}
if (upgrade
&& !isParameterUpOrDowngradeValid(dbTargetParameter,
voTargetParameter)) {
String sourceProductId = dbSourceProduct
.getTemplateOrSelf().getProductId();
String targetProductId = dbTargetProduct
.getTemplateOrSelf().getProductId();
SubscriptionMigrationException e = new SubscriptionMigrationException(
"Incompatible parameter found",
Reason.INCOMPATIBLE_PARAMETER, new Object[] {
subscription.getSubscriptionId(),
sourceProductId,
targetProductId,
voTargetParameter.getParameterDefinition()
.getParameterId() });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
e,
LogMessageIdentifier.WARN_NOT_CONFIGURABLE_PARAMETER_OF_SUBSCRIPTION_MODIFIED,
dataManager.getCurrentUser().getUserId(),
dbParameterId,
Long.toString(dbSourceProduct.getKey()));
throw e;
}
if (dbTargetParameter.isValueSet()) {
// if currently no value is set, even null or empty as new
// value mean a change
if (!dbTargetParameter.getValue().equals(
voTargetParameter.getValue())) {
result = true;
}
} else {
// if no value is currently set, the new value only needs to
// be set if not null and not empty
if (voTargetParameter.getValue() != null
&& voTargetParameter.getValue().trim().length() > 0) {
result = true;
}
}
}
}
return result;
}
/**
* Verifies the version of a parameter.
*
* @param dbTargetProduct
* target product
* @param voTargetParameters
* VO target parameters
* @throws ConcurrentModificationException
* Is thrown if the parameter version changed or the parameter
* does not exist anymore.
*/
void verifyIfParameterConcurrentlyChanged(Product dbTargetProduct,
List<VOParameter> voTargetParameters, boolean upgrade)
throws ServiceChangedException, ConcurrentModificationException {
List<Parameter> dbTargetParameterList;
if (dbTargetProduct.getParameterSet() == null
|| dbTargetProduct.getParameterSet().getParameters() == null) {
dbTargetParameterList = new LinkedList<>();
} else {
dbTargetParameterList = dbTargetProduct.getParameterSet()
.getParameters();
}
if (upgrade
&& dbTargetParameterList.size() != voTargetParameters.size()) {
// Parameter changed, thus throw ex
throw new ServiceChangedException(
ServiceChangedException.Reason.SERVICE_MODIFIED);
}
Map<String, Parameter> dbParameterMap = new HashMap<>();
for (Parameter parameter : dbTargetParameterList) {
dbParameterMap.put(parameter.getParameterDefinition()
.getParameterId(), parameter);
}
for (VOParameter voParameter : voTargetParameters) {
Parameter dbParameter = dbParameterMap.get(voParameter
.getParameterDefinition().getParameterId());
if (dbParameter == null) {
String message = String.format(
"Parameter '%s' does not exist.", voParameter
.getParameterDefinition().getParameterId());
throw new ServiceChangedException(message);
}
BaseAssembler.verifyVersionAndKey(dbParameter, voParameter);
}
}
/**
* Matrix : <br/>
* 1. NOT CONFIGURABLE or CONFIGURABLE --> NOT CONFIGURABLE = OK, if values
* are identical or parameter modification type is one time<br/>
*
* 2. Otherwise true is returned
*
* @param dbParameter
* source (subscription) parameter
* @param targetParameter
* VO target parameter
* @return see matrix. False is also returned if the parameter id of the
* both parameters are not the same
*/
boolean isParameterUpOrDowngradeValid(Parameter dbParameter,
VOParameter targetParameter) {
if (!dbParameter
.getParameterDefinition()
.getParameterId()
.equals(targetParameter.getParameterDefinition()
.getParameterId())) {
return false;
}
if (dbParameter.getParameterDefinition().getModificationType() != targetParameter
.getParameterDefinition().getModificationType()) {
return false;
}
boolean targetOneTime = targetParameter.getParameterDefinition()
.getModificationType()
.equals(ParameterModificationType.ONE_TIME);
// non-configurable non-onetime parameter now only has default value,
// bug #9422
return !(!dbParameter.isConfigurable() && !targetOneTime)
|| compareParameterValue(dbParameter, targetParameter);
}
/**
* Compares the value of both parameters. A NULL value and empty String are
* treated identically.
*
* @param sourceParameter
* source (subscription) parameter
* @param targetParameter
* target parameter
* @return true, if identical, otherwise false
*/
private boolean compareParameterValue(Parameter sourceParameter,
Parameter targetParameter) {
String sourceParameterValue = sourceParameter.getValue() == null ? ""
: sourceParameter.getValue().trim();
String targetParameterValue = targetParameter.getValue() == null ? ""
: targetParameter.getValue().trim();
return sourceParameterValue.equals(targetParameterValue);
}
/**
* Compares the value of both parameters. A NULL value and empty String are
* treated identically.
*
* @param sourceParameter
* source (subscription) parameter
* @param targetParameter
* VO target parameter
* @return true, if identical, otherwise false
*/
private boolean compareParameterValue(Parameter sourceParameter,
VOParameter targetParameter) {
String sourceParameterValue = sourceParameter.getValue() == null ? ""
: sourceParameter.getValue().trim();
String targetParameterValue = targetParameter.getValue() == null ? ""
: targetParameter.getValue().trim();
return sourceParameterValue.equals(targetParameterValue);
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<String> getSubscriptionIdentifiers()
throws OrganizationAuthoritiesException {
Organization org = dataManager.getCurrentUser().getOrganization();
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING);
return getSubscriptionDao().getSubscriptionIdsForMyCustomers(org,
states);
}
private List<Subscription> getQueryResultListSubIdsAndOrgs(
Set<SubscriptionStatus> states) {
List<Subscription> result = new ArrayList<>();
result.addAll(executeQueryLoadSubIdsAndOrgsForMyCustomers(states));
Organization org = dataManager.getCurrentUser().getOrganization();
if (org.hasRole(OrganizationRoleType.SUPPLIER)) {
result.addAll(executeQueryLoadSubIdsAndOrgsForMyBrokerCustomers());
}
return result;
}
List<Subscription> getQueryResultListSubIdsAndOrgs(
Set<SubscriptionStatus> states, Pagination pagination) {
List<Subscription> result = new ArrayList<>();
Organization org = dataManager.getCurrentUser().getOrganization();
if (org.hasRole(OrganizationRoleType.SUPPLIER)) {
result.addAll(executeQueryLoadSubIdsAndOrgsForMyBrokerCustomers(
states, pagination));
} else {
result.addAll(executeQueryLoadSubIdsAndOrgsForMyCustomers(states,
pagination));
}
return result;
}
List<Subscription> executeQueryLoadSubIdsAndOrgsForMyCustomers(
Set<SubscriptionStatus> states) {
Organization org = dataManager.getCurrentUser().getOrganization();
return getSubscriptionDao().getSubscriptionsForMyCustomers(org, states);
}
List<Subscription> executeQueryLoadSubIdsAndOrgsForMyBrokerCustomers() {
Organization org = dataManager.getCurrentUser().getOrganization();
return getSubscriptionDao().getSubscriptionsForMyBrokerCustomers(org);
}
List<Subscription> executeQueryLoadSubIdsAndOrgsForMyCustomers(
Set<SubscriptionStatus> states, Pagination pagination) {
return getSubscriptionDao().getSubscriptionsForMyCustomers(
dataManager.getCurrentUser(), states, pagination);
}
List<Subscription> executeQueryLoadSubIdsAndOrgsForMyBrokerCustomers(
Set<SubscriptionStatus> states, Pagination pagination) {
return getSubscriptionDao().getSubscriptionsForMyBrokerCustomers(
dataManager.getCurrentUser(), states, pagination);
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<VOOrganization> getCustomersForSubscriptionId(
String subscriptionId) throws OrganizationAuthoritiesException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
List<VOOrganization> result = new ArrayList<>();
Organization offerer = dataManager.getCurrentUser().getOrganization();
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING);
List<Organization> customers = getOrganizationDao()
.getCustomersForSubscriptionId(offerer, subscriptionId, states);
LocalizerFacade lf = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
for (Organization customer : customers) {
result.add(OrganizationAssembler.toVOOrganization(customer, false,
lf, PerformanceHint.ONLY_IDENTIFYING_FIELDS));
}
return result;
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public boolean expireOverdueSubscriptions(long currentTime) {
return terminateBean.expireOverdueSubscriptions(currentTime);
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public boolean expireSubscription(Subscription subscriptionToExpire) {
return terminateBean.expireSubscription(subscriptionToExpire);
}
/**
* Checks if the usercount of the subscription is lower or equal to the
* value of the product parameter NAMED_USER. If this condition does not
* hold, an ProductParameterException will be thrown.
*
* @param subscription
* The subscription to be checked.
* @throws ServiceParameterException
* Thrown in case the user count of the subscription is greater
* than the value of the product parameter NAMED_USER
*/
void verifyParameterNamedUser(Subscription subscription)
throws ServiceParameterException {
if (subscription == null) {
return;
}
ParameterSet parameterSet = subscription.getParameterSet();
if (parameterSet == null || parameterSet.getParameters() == null) {
return;
}
for (Parameter parameter : parameterSet.getParameters()) {
if (parameter.getParameterDefinition().getParameterType() == ParameterType.PLATFORM_PARAMETER
&& PlatformParameterIdentifiers.NAMED_USER.equals(parameter
.getParameterDefinition().getParameterId())) {
// if it is not defined to be mandatory, it can be empty
if (Strings.isEmpty(parameter.getValue())) {
return;
}
try {
// If a value is set, it must be ensured by validation that
// it is an integer - so the NumberFormatException should
// not happen
if (subscription.getActiveUsers().size() > Integer
.parseInt(parameter.getValue())) {
sessionCtx.setRollbackOnly();
String text = "Subscription '"
+ subscription.getSubscriptionId()
+ "'/Product '"
+ subscription.getProduct().getProductId()
+ "'";
ServiceParameterException e = new ServiceParameterException(
text, ParameterType.PLATFORM_PARAMETER,
PlatformParameterIdentifiers.NAMED_USER,
new Object[] { parameter.getValue(),
subscription.getSubscriptionId() });
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_TOO_MANY_NAMED_USER_FOR_SUBSCRIPTION,
subscription.getSubscriptionId(), subscription
.getProduct().getProductId());
throw e;
}
} catch (NumberFormatException e) {
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_PROCESS_NAMED_USER_FAILED_AS_NUMBER_FORMAT,
parameter.getValue(), subscription.getProduct()
.getProductId());
}
}
}
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void informProductAboutNewUsers(Subscription sub,
List<PlatformUser> users) throws SubscriptionStateException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
stateValidator.checkInformProductAboutNewUsers(sub);
if (!canModifyApplicationUsers(sub)) {
return;
}
List<UsageLicense> licenses = getUsageLicensesForUsers(sub, users);
User[] createdUsers = appManager.createUsers(sub, licenses);
mapApplicationUserIdToLicense(licenses, createdUsers);
}
/**
* Maps the application user id back to the usage license and sets the
* affected usage license dirty
*
* @param licenses
* the usage licenses to update
* @param createdUsers
* the user array containing the application user id
*/
private void mapApplicationUserIdToLicense(List<UsageLicense> licenses,
User[] createdUsers) {
if (createdUsers == null) {
return;
}
String applicationUserId;
for (UsageLicense license : licenses) {
for (User createdUser : createdUsers) {
applicationUserId = createdUser.getApplicationUserId();
if (createdUser.getUserId().equals(
license.getUser().getUserId())
&& applicationUserId != null) {
license.setApplicationUserId(applicationUserId);
break;
}
}
}
}
/**
* Determines the usage license for the given users of the subscription.
*
* @param sub
* the subscription to get the usage licenses from
* @param users
* the users to get the usage licenses for
* @return the list of usage licenses
*/
private List<UsageLicense> getUsageLicensesForUsers(Subscription sub,
List<PlatformUser> users) {
List<UsageLicense> result = new ArrayList<>();
List<UsageLicense> licenses = sub.getUsageLicenses();
for (PlatformUser user : users) {
for (UsageLicense license : licenses) {
if (user.getKey() == license.getUser().getKey()) {
result.add(license);
}
}
}
return result;
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void abortAsyncSubscription(String subscriptionId,
String organizationId, List<VOLocalizedText> reason)
throws ObjectNotFoundException, SubscriptionStateException,
OrganizationAuthoritiesException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
manageBean.validateTechnoloyProvider(subscription);
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
throw new SubscriptionStateException(
"Operation not allowed for subscription "
+ subscription.getSubscriptionId(),
SubscriptionStateException.Reason.ONLY_PENDING);
}
abortSubscription(subscriptionId, subscription);
removeLocalizedResources(reason, subscription);
deleteProduct(subscription);
List<PlatformUser> receivers = loadReceiversForAbortAsyncSubscription(subscription);
sendSubscriptionAbortEmail(subscriptionId, organizationId,
subscription, receivers);
}
private void deleteProduct(Subscription subscription) {
Product product = subscription.getProduct();
product.setStatus(ServiceStatus.DELETED);
}
private void abortSubscription(String subscriptionId,
Subscription subscription) {
subscription.setStatus(SubscriptionStatus.INVALID);
subscription.setSubscriptionId(subscriptionId + "#"
+ String.valueOf(System.currentTimeMillis()));
}
void removeLocalizedResources(List<VOLocalizedText> reason,
Subscription subscription) {
long key = subscription.getKey();
localizer.removeLocalizedValues(key,
LocalizedObjectTypes.SUBSCRIPTION_PROVISIONING_PROGRESS);
localizer
.storeLocalizedResources(
key,
LocalizedObjectTypes.SUBSCRIPTION_PROVISIONING_PROGRESS,
reason);
}
void sendSubscriptionAbortEmail(String subscriptionId,
String organizationId, Subscription subscription,
List<PlatformUser> receivers) {
for (PlatformUser platformUser : receivers) {
LocalizerFacade facade = new LocalizerFacade(localizer,
platformUser.getLocale());
String text = facade.getText(subscription.getKey(),
LocalizedObjectTypes.SUBSCRIPTION_PROVISIONING_PROGRESS);
try {
commService.sendMail(platformUser,
EmailType.SUBSCRIPTION_INVALIDATED, new Object[] {
subscriptionId, organizationId, text },
subscription.getMarketplace());
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_INVALIDATION_SUBSCRIPTION_CONFIRMING_FAILED);
}
}
}
/**
* The mail for aborting asynchronous subscription is sent to:
*
* - administrators of the technology provider organization;<br/>
* - administrators of the customer organization;<br/>
* - subscription owner if it is not already administrator.
*/
List<PlatformUser> loadReceiversForAbortAsyncSubscription(
Subscription subscription) {
return manageBean
.getCustomerAndTechnicalProductAdminForSubscription(subscription);
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void completeAsyncSubscription(String subscriptionId,
String organizationId, VOInstanceInfo instanceInfo)
throws ObjectNotFoundException, SubscriptionStateException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException,
OrganizationAuthoritiesException, OperationNotPermittedException,
ValidationException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("instance", instanceInfo);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
String productInstanceId = instanceInfo.getInstanceId();
TechnicalProduct techProduct = subscription.getProduct()
.getTechnicalProduct();
if (getSubscriptionDao().checkIfProductInstanceIdExists(
productInstanceId, techProduct)) {
ValidationException ex = new ValidationException(
"The product instance ID already exist");
LOG.logError(
Log4jLogger.SYSTEM_LOG,
ex,
LogMessageIdentifier.ERROR_PRODUCT_INSTANCE_ID_ALREADY_EXIST);
throw ex;
}
updateInstanceInfoForCompletion(subscription, instanceInfo);
manageBean.validateTechnoloyProvider(subscription);
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
throw new SubscriptionStateException(
"Operation not allowed for subscription "
+ subscription.getSubscriptionId(),
SubscriptionStateException.Reason.ONLY_PENDING);
}
subscription.setActivationDate(Long.valueOf(DateFactory.getInstance()
.getTransactionTime()));
boolean deactivateInstance = !modUpgBean
.isPaymentValidOrFree(subscription);
if (deactivateInstance) {
subscription.setStatus(SubscriptionStatus.SUSPENDED);
} else {
activateSubscriptionFirstTime(subscription);
}
NotifyProvisioningServicePayload payload = new NotifyProvisioningServicePayload(
subscription.getKey(), deactivateInstance);
TaskMessage message = new TaskMessage(
NotifyProvisioningServiceHandler.class, payload);
tqs.sendAllMessages(Collections.singletonList(message));
PriceModel pm = subscription.getProduct().getPriceModel();
pm.setProvisioningCompleted(true);
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void updateAsyncSubscriptionProgress(String subscriptionId,
String organizationId, List<VOLocalizedText> progress)
throws ObjectNotFoundException, SubscriptionStateException,
OrganizationAuthoritiesException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
manageBean.validateTechnoloyProvider(subscription);
if (subscription.getStatus() != SubscriptionStatus.PENDING) {
throw new SubscriptionStateException(
"Operation not allowed for subscription "
+ subscription.getSubscriptionId(),
SubscriptionStateException.Reason.ONLY_PENDING);
}
localizer.storeLocalizedResources(subscription.getKey(),
LocalizedObjectTypes.SUBSCRIPTION_PROVISIONING_PROGRESS,
progress);
}
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public boolean notifyAboutTimedoutSubscriptions(long currentTime) {
// we could also use a separate query inclusing the checked conditions
List<Subscription> subscriptions = getSubscriptionDao()
.getSubscriptionsByStatus(SubscriptionStatus.PENDING);
for (Subscription subscription : subscriptions) {
Long timeout = subscription.getProduct().getTechnicalProduct()
.getProvisioningTimeout();
if (!subscription.isTimeoutMailSent()
&& subscription.getCreationDate().longValue()
+ timeout.longValue() < currentTime) {
List<PlatformUser> users = subscription.getProduct()
.getTechnicalProduct().getOrganization()
.getPlatformUsers();
if (notifyTechnicalAdminsAboutTimeout(subscription, users)) {
// if at least one mail was sent, set the mail sent flag of
// the subscription
subscription.setTimeoutMailSent(true);
}
}
}
return true;
}
/**
* Tries to send a notification mail to the admin users contained in the
* list of users of the technical product owner organization informing about
* a timed out pending subscription.
*
* @param subscription
* the subscription that timed ot in pending state
* @param users
* the users of the organization owning the technical product
* @return <code>true</code> if at leas one mail was sent otherwise
* <code>false</code>
*/
private boolean notifyTechnicalAdminsAboutTimeout(
Subscription subscription, List<PlatformUser> users) {
boolean result = false;
String organizationId = subscription.getOrganization()
.getOrganizationId();
String subscriptionId = subscription.getSubscriptionId();
for (PlatformUser user : users) {
if (!user.isOrganizationAdmin()) {
continue;
}
try {
commService.sendMail(user, EmailType.SUBSCRIPTION_TIMEDOUT,
new Object[] { subscriptionId, organizationId },
subscription.getMarketplace());
// at least one admin could be informed
result = true;
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_TIMEOUT_OF_SUBSCRIPTION_NOTIFYING_FAILED);
}
}
return result;
}
/**
* Checks if the users of the subscription can be modified. this is not
* possible if the subscription is in pending or invalid state because no
* product instance is there in this case.
*
* @param subscription
* the subscription to modify the application side users for
* @return <code>true</code> if product instance can be informed otherwise
* <code>false</code>
*/
private boolean canModifyApplicationUsers(Subscription subscription) {
return !(subscription.getStatus() == SubscriptionStatus.PENDING || subscription
.getStatus() == SubscriptionStatus.INVALID);
}
/**
* It returns a list of VOSubscriptionIdAndOrganizations objects, which
* contain the subscriptionIdentifier and the associated customers of the
* subscription in form of list.If there are no subscriptions an empty list
* is returned.
*
* The role of organization as a supplier, a broker or a reseller is needed
* to execute this method.
*
* @return List<VOSubscriptionIdAndOrganizations>
*/
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<VOSubscriptionIdAndOrganizations> getCustomerSubscriptions()
throws OrganizationAuthoritiesException {
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING);
LocalizerFacade lf = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
List<Subscription> queryResultList = getQueryResultListSubIdsAndOrgs(states);
Map<String, VOSubscriptionIdAndOrganizations> mapSubIdsAndOrgs = getSubIdsAndOrgs(
lf, queryResultList);
return new ArrayList<VOSubscriptionIdAndOrganizations>(
mapSubIdsAndOrgs.values());
}
/**
* It returns a list of VOSubscriptionIdAndOrganizations objects, which
* contain the subscriptionIdentifier and the associated customers of the
* subscription in form of list.If there are no subscriptions an empty list
* is returned.
*
* The role of organization as a supplier, a broker or a reseller is needed
* to execute this method.
*
* @return List<VOSubscriptionIdAndOrganizations>
*/
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<VOSubscriptionIdAndOrganizations> getSubscriptionsForTerminate()
throws OrganizationAuthoritiesException {
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING, SubscriptionStatus.EXPIRED);
LocalizerFacade lf = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
List<Subscription> queryResultList = getQueryResultListSubIdsAndOrgs(states);
Map<String, VOSubscriptionIdAndOrganizations> mapSubIdsAndOrgs = getSubIdsAndOrgs(
lf, queryResultList);
return new ArrayList<VOSubscriptionIdAndOrganizations>(
mapSubIdsAndOrgs.values());
}
private Map<String, VOSubscriptionIdAndOrganizations> getSubIdsAndOrgs(
LocalizerFacade lf, List<Subscription> subscriptionList) {
Map<String, VOSubscriptionIdAndOrganizations> mapSubIdsAndOrgs = new LinkedHashMap<>();
for (Subscription subscription : subscriptionList) {
String subId = subscription.getSubscriptionId();
Organization customer = subscription.getOrganization();
if (mapSubIdsAndOrgs.containsKey(subId)) {
VOSubscriptionIdAndOrganizations subAndOrgs = mapSubIdsAndOrgs
.get(subId);
List<VOOrganization> customersForSubId = subAndOrgs
.getOrganizations();
customersForSubId.add(OrganizationAssembler.toVOOrganization(
customer, false, lf,
PerformanceHint.ONLY_IDENTIFYING_FIELDS));
subAndOrgs.setOrganizations(customersForSubId);
mapSubIdsAndOrgs.put(subId, subAndOrgs);
} else {
VOSubscriptionIdAndOrganizations subAndOrgs = new VOSubscriptionIdAndOrganizations();
subAndOrgs.setSubscriptionId(subId);
List<VOOrganization> customers = new ArrayList<>();
customers.add(OrganizationAssembler.toVOOrganization(customer,
false, lf, PerformanceHint.ONLY_IDENTIFYING_FIELDS));
subAndOrgs.setOrganizations(customers);
mapSubIdsAndOrgs.put(subId, subAndOrgs);
}
}
return mapSubIdsAndOrgs;
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public VOSubscriptionDetails getSubscriptionForCustomer(
String organizationId, String subscriptionId)
throws ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("subscriptionId", subscriptionId);
// find organization of customer
Organization customerTmpl = new Organization();
customerTmpl.setOrganizationId(organizationId);
Organization customer = (Organization) dataManager
.getReferenceByBusinessKey(customerTmpl);
final PlatformUser currentUser = dataManager.getCurrentUser();
PermissionCheck.sellerOfCustomer(currentUser.getOrganization(),
customer, LOG, sessionCtx);
Subscription subscriptionTmpl = new Subscription();
subscriptionTmpl.setSubscriptionId(subscriptionId);
subscriptionTmpl.setOrganizationKey(customer.getKey());
Subscription subscription = (Subscription) dataManager
.getReferenceByBusinessKey(subscriptionTmpl);
// fill subscription VO
LocalizerFacade facade = new LocalizerFacade(localizer,
currentUser.getLocale());
VOSubscriptionDetails voSubscriptionDetail = SubscriptionAssembler
.toVOSubscriptionDetails(subscription, facade);
// log view subscription
audit.viewSubscription(dataManager, subscription, customer);
return voSubscriptionDetail;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public List<VORoleDefinition> getServiceRolesForSubscription(
String subscriptionId) throws ObjectNotFoundException,
OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
Subscription sub = manageBean.checkSubscriptionOwner(subscriptionId, 0);
return getServiceRolesForSubscription(sub);
}
@Override
public List<VORoleDefinition> getServiceRolesForSubscription(
long subscriptionKey) throws ObjectNotFoundException,
OperationNotPermittedException {
Subscription sub = manageBean.checkSubscriptionOwner(null,
subscriptionKey);
return getServiceRolesForSubscription(sub);
}
private List<VORoleDefinition> getServiceRolesForSubscription(
Subscription subscription) {
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
List<RoleDefinition> roleDefinitions = subscription.getProduct()
.getTechnicalProduct().getRoleDefinitions();
return RoleAssembler.toVORoleDefinitions(roleDefinitions, facade);
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public List<VORoleDefinition> getServiceRolesForService(VOService service)
throws ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("service", service);
Product prod = dataManager
.getReference(Product.class, service.getKey());
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
List<RoleDefinition> roleDefinitions = prod.getTechnicalProduct()
.getRoleDefinitions();
return RoleAssembler.toVORoleDefinitions(roleDefinitions, facade);
}
@Override
public void executeServiceOperation(VOSubscription subscription,
VOTechnicalServiceOperation operation)
throws ObjectNotFoundException, OperationNotPermittedException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException,
OrganizationAuthoritiesException, ConcurrentModificationException,
ValidationException, SubscriptionStateException,
NonUniqueBusinessKeyException {
ArgumentValidator.notNull("subscription", subscription);
ArgumentValidator.notNull("operation", operation);
Subscription sub = manageBean.loadSubscription(
subscription.getSubscriptionId(), 0);
stateValidator.checkExecuteServiceOperationAllowed(sub);
TechnicalProductOperation op = dataManager.getReference(
TechnicalProductOperation.class, operation.getKey());
BaseAssembler.verifyVersionAndKey(sub, subscription);
BaseAssembler.verifyVersionAndKey(op, operation);
List<VOServiceOperationParameter> list = operation
.getOperationParameters();
Map<String, String> params = new HashMap<>();
if (list != null) {
for (VOServiceOperationParameter p : list) {
params.put(p.getParameterId(), p.getParameterValue());
}
}
checkIfParamsModified(op, list);
String transactionid = IdGenerator.generateArtificialIdentifier();
OperationResult result = manageBean.executeServiceOperation(sub, op,
params, transactionid);
createOperationRecord(sub, op, transactionid, result.isAsyncExecution());
}
private void createOperationRecord(Subscription subscription,
TechnicalProductOperation operation, String transactionid,
boolean isAsyncExecution) throws NonUniqueBusinessKeyException {
Date executiondate = DateFactory.getInstance().getTransactionDate();
OperationRecord record = givenOperationRecord(subscription, operation,
executiondate, transactionid, isAsyncExecution);
operationRecordBean.createOperationRecord(record);
}
OperationRecord givenOperationRecord(Subscription subscription,
TechnicalProductOperation operation, Date executiondate,
String transactionid, boolean isAsyncExecution) {
OperationRecord record = new OperationRecord();
record.setTransactionid(transactionid);
record.setSubscription(subscription);
record.setTechnicalProductOperation(operation);
record.setExecutiondate(executiondate);
record.setUser(dataManager.getCurrentUser());
if (isAsyncExecution) {
record.setStatus(OperationStatus.RUNNING);
} else {
record.setStatus(OperationStatus.COMPLETED);
}
return record;
}
private void checkIfParamsModified(TechnicalProductOperation op,
List<VOServiceOperationParameter> list)
throws ConcurrentModificationException {
List<OperationParameter> opParams = op.getParameters();
Map<Long, OperationParameter> opParamsMap = new HashMap<>();
if (opParams != null) {
for (OperationParameter p : opParams) {
opParamsMap.put(Long.valueOf(p.getKey()), p);
}
}
if (opParamsMap.size() != list.size()) {
throw new ConcurrentModificationException();
}
for (VOServiceOperationParameter parameter : list) {
OperationParameter param = opParamsMap.get(Long.valueOf(parameter
.getKey()));
if (param == null) {
ConcurrentModificationException cme = new ConcurrentModificationException(
parameter);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, cme,
LogMessageIdentifier.WARN_CONCURRENT_MODIFICATION,
parameter.getClass().getSimpleName());
throw cme;
} else {
BaseAssembler.verifyVersionAndKey(param, parameter);
}
}
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "RESELLER_MANAGER" })
public void terminateSubscription(VOSubscription subscrVO, String reason)
throws ObjectNotFoundException, OrganizationAuthoritiesException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException,
ConcurrentModificationException, SubscriptionStateException {
ArgumentValidator.notNull("subscription", subscrVO);
Subscription subscription = loadSubscription(subscrVO.getKey());
BaseAssembler.verifyVersionAndKey(subscription, subscrVO);
// Remove corresponding operation record of the subscription
operationRecordBean.removeOperationsForSubscription(subscription
.getKey());
terminateBean.terminateSubscription(subscription, reason);
}
@Override
public boolean hasCurrentUserSubscriptions() {
String userKey = sessionCtx.getCallerPrincipal().getName();
Long userKeyLong;
try {
userKeyLong = Long.valueOf(userKey);
} catch (NumberFormatException e) {
SaaSSystemException saaSSystemException = new SaaSSystemException(e);
LOG.logError(Log4jLogger.SYSTEM_LOG, saaSSystemException,
LogMessageIdentifier.ERROR_WRONG_USER_KEY_IN_SESSION,
userKey);
throw saaSSystemException;
}
Long count = getSubscriptionDao().hasCurrentUserSubscriptions(
userKeyLong, VISIBLE_SUBSCRIPTION_STATUS);
return count.longValue() > 0;
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER",
"UNIT_ADMINISTRATOR" })
public VOSubscriptionDetails modifySubscriptionPaymentData(
VOSubscription subscription, VOBillingContact billingContact,
VOPaymentInfo paymentInfo) throws ObjectNotFoundException,
ConcurrentModificationException, OperationNotPermittedException,
PaymentInformationException, SubscriptionStateException,
PaymentDataException, TechnicalServiceNotAliveException,
TechnicalServiceOperationException {
ArgumentValidator.notNull("subscription", subscription);
Subscription sub = manageBean.checkSubscriptionOwner(
subscription.getSubscriptionId(), subscription.getKey());
PlatformUser user = dataManager.getCurrentUser();
Organization customer = user.getOrganization();
PermissionCheck.owns(sub, customer, LOG);
BaseAssembler.verifyVersionAndKey(sub, subscription);
EnumSet<SubscriptionStatus> set = EnumSet.of(
SubscriptionStatus.DEACTIVATED, SubscriptionStatus.EXPIRED,
SubscriptionStatus.INVALID);
if (set.contains(sub.getStatus())) {
Object[] params = new Object[] { sub.getStatus().name() };
SubscriptionStateException sse = new SubscriptionStateException(
SubscriptionStateException.Reason.SUBSCRIPTION_INVALID_STATE,
null, params);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, sse,
LogMessageIdentifier.WARN_SUBSCRIPTION_STATE_INVALID, sub
.getStatus().name());
throw sse;
}
if (!sub.getPriceModel().isChargeable()) {
if (billingContact != null || paymentInfo != null) {
PaymentDataException pde = new PaymentDataException(
"No payment info required for a non-chargeable price model",
PaymentDataException.Reason.NO_PAYMENT_REQUIRED);
LOG.logWarn(Log4jLogger.SYSTEM_LOG, pde,
LogMessageIdentifier.WARN_NO_PAYMENT_INFO_REQUIRED);
throw pde;
}
}
PaymentInfo pi = null;
BillingContact bc = null;
if (sub.getPriceModel().isChargeable()) {
PaymentDataValidator.validateNotNull(paymentInfo, billingContact);
pi = dataManager.getReference(PaymentInfo.class,
paymentInfo.getKey());
bc = dataManager.getReference(BillingContact.class,
billingContact.getKey());
PermissionCheck.owns(pi, customer, LOG);
PermissionCheck.owns(bc, customer, LOG);
BaseAssembler.verifyVersionAndKey(pi, paymentInfo);
BaseAssembler.verifyVersionAndKey(bc, billingContact);
PaymentDataValidator.validatePaymentTypeSupportedBySupplier(
customer, sub.getProduct(), pi.getPaymentType());
PaymentDataValidator.validatePaymentInfoDataForUsage(pi);
SubscriptionStatus current = sub.getStatus();
if (current.isSuspendedOrSuspendedUpd()) {
try {
appManager.activateInstance(sub);
} catch (TechnicalServiceNotAliveException
| TechnicalServiceOperationException e) {
sessionCtx.setRollbackOnly();
throw e;
}
sub.setStatus(current.getNextForPaymentTypeRevoked());
}
}
// log before subscription changed!
audit.editPaymentType(dataManager, sub, pi);
audit.editBillingAddress(dataManager, sub, bc);
// change subscription
sub.setPaymentInfo(pi);
sub.setBillingContact(bc);
// flush to get the correct version of the subscription
dataManager.flush();
return SubscriptionAssembler.toVOSubscriptionDetails(sub,
new LocalizerFacade(localizer, user.getLocale()));
}
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "SUBSCRIPTION_MANAGER" })
public void reportIssue(String subscriptionId, String subject,
String issueText) throws IllegalArgumentException,
ObjectNotFoundException, OperationNotPermittedException,
MailOperationException, ValidationException {
manageBean.reportIssue(subscriptionId, subject, issueText);
}
void activateSubscriptionFirstTime(Subscription subscription) {
subscription.setStatus(SubscriptionStatus.ACTIVE);
Organization chargingOrganization = subscription.getProduct()
.determineChargingOrganization();
subscription.setCutOffDay(chargingOrganization.getCutOffDay());
}
/**
* Check if PaymentInfo or BillingContact is concurrently modified.
*
* @param paymentInfo
* the existing PaymentInfo stored in database
* @param billingContact
* the existing BillingContact stored in database
* @param voPaymentInfo
* @param voBillingContact
* @throws ConcurrentModificationException
*/
void validatePaymentInfoAndBillingContact(PaymentInfo paymentInfo,
BillingContact billingContact, VOPaymentInfo voPaymentInfo,
VOBillingContact voBillingContact)
throws ConcurrentModificationException {
BaseAssembler.verifyVersionAndKey(paymentInfo, voPaymentInfo);
BaseAssembler.verifyVersionAndKey(billingContact, voBillingContact);
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<Subscription> getSubscriptionsForManagers()
throws OrganizationAuthoritiesException {
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING, SubscriptionStatus.EXPIRED,
SubscriptionStatus.PENDING_UPD, SubscriptionStatus.SUSPENDED,
SubscriptionStatus.SUSPENDED_UPD);
return getQueryResultListSubIdsAndOrgs(states);
}
@Override
@RolesAllowed({ "SERVICE_MANAGER", "BROKER_MANAGER", "RESELLER_MANAGER" })
public List<Subscription> getSubscriptionsForManagers(Pagination pagination)
throws OrganizationAuthoritiesException {
Set<SubscriptionStatus> states = EnumSet.of(SubscriptionStatus.ACTIVE,
SubscriptionStatus.PENDING, SubscriptionStatus.EXPIRED,
SubscriptionStatus.PENDING_UPD, SubscriptionStatus.SUSPENDED,
SubscriptionStatus.SUSPENDED_UPD);
return getQueryResultListSubIdsAndOrgs(states, pagination);
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void completeAsyncModifySubscription(String subscriptionId,
String organizationId, VOInstanceInfo instance)
throws ObjectNotFoundException, SubscriptionStateException,
TechnicalServiceNotAliveException,
TechnicalServiceOperationException,
OrganizationAuthoritiesException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("instance", instance);
Subscription subscription = modUpgBean
.findSubscriptionForAsyncCallBack(subscriptionId,
organizationId);
stateValidator.checkCompleteModifyAllowed(subscription);
updateInstanceInfoForCompletion(subscription, instance);
manageBean.validateTechnoloyProvider(subscription);
modUpgBean.setStatusForModifyComplete(subscription);
Map<String, Parameter> paramMap = new HashMap<>();
if (subscription.getParameterSet() != null) {
for (Parameter parameter : subscription.getParameterSet()
.getParameters()) {
paramMap.put(parameter.getParameterDefinition()
.getParameterId(), parameter);
}
}
Product asyncTempProduct = subscription.getAsyncTempProduct();
if (asyncTempProduct.getParameterSet() != null) {
for (Parameter tempParam : asyncTempProduct.getParameterSet()
.getParameters()) {
String parameterID = tempParam.getParameterDefinition()
.getParameterId();
Parameter param = paramMap.get(parameterID);
if (param != null) {
param.setValue(tempParam.getValue());
}
}
}
subscription.setAsyncTempProduct(null);
dataManager.remove(asyncTempProduct);
modUpgBean.updateSubscriptionAttributesForAsyncUpdate(subscription);
List<PlatformUser> receivers = manageBean
.getCustomerAdminsAndSubscriptionOwner(subscription);
for (PlatformUser platformUser : receivers) {
try {
commService.sendMail(platformUser,
EmailType.SUBSCRIPTION_PARAMETER_MODIFIED,
new Object[] { subscriptionId },
subscription.getMarketplace());
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_MODIFY_PARAMETER_OF_SUBSCRIPTION_CONFIRMING_FAILED);
}
}
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void abortAsyncModifySubscription(String subscriptionId,
String organizationId, List<VOLocalizedText> reason)
throws ObjectNotFoundException, SubscriptionStateException,
OrganizationAuthoritiesException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
Subscription subscription = modUpgBean
.findSubscriptionForAsyncCallBack(subscriptionId,
organizationId);
stateValidator.checkAbortAllowedForModifying(subscription);
abortAsyncUpgradeOrModifySubscription(subscription, organizationId,
reason);
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void completeAsyncUpgradeSubscription(String subscriptionId,
String organizationId, VOInstanceInfo instance)
throws ObjectNotFoundException, TechnicalServiceOperationException,
OperationNotPermittedException, SubscriptionStateException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("instance", instance);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
stateValidator.checkCompleteUpgradeAllowed(subscription);
updateInstanceInfoForCompletion(subscription, instance);
manageBean.validateTechnoloyProvider(subscription);
Product initialProduct = subscription.getProduct();
Product asyncTempProduct = subscription.getAsyncTempProduct();
subscription.bindToProduct(asyncTempProduct);
subscription.setAsyncTempProduct(null);
modUpgBean.updateSubscriptionAttributesForAsyncUpgrade(subscription);
modUpgBean.setStatusForUpgradeComplete(subscription);
String oldServiceId = initialProduct.getTemplate() != null ? initialProduct
.getTemplate().getProductId() : initialProduct.getProductId();
String newServiceId = asyncTempProduct.getTemplate() != null ? asyncTempProduct
.getTemplate().getProductId() : asyncTempProduct.getProductId();
dataManager.remove(initialProduct);
dataManager.flush();
PriceModel pm = subscription.getProduct().getPriceModel();
pm.setProvisioningCompleted(true);
if (subscription.getStatus() == SubscriptionStatus.SUSPENDED) {
manageBean.suspend(subscription);
}
modUpgBean.sendConfirmUpgradationEmail(subscription, oldServiceId,
newServiceId, instance.getAccessInfo());
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void abortAsyncUpgradeSubscription(String subscriptionId,
String organizationId, List<VOLocalizedText> reason)
throws ObjectNotFoundException, SubscriptionStateException,
OrganizationAuthoritiesException, OperationNotPermittedException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
stateValidator.checkAbortAllowedForUpgrading(subscription);
abortAsyncUpgradeOrModifySubscription(subscription, organizationId,
reason);
}
void abortAsyncUpgradeOrModifySubscription(Subscription subscription,
String organizationId, List<VOLocalizedText> reason)
throws OperationNotPermittedException {
manageBean.validateTechnoloyProvider(subscription);
final SubscriptionStatus currentState = subscription.getStatus();
subscription.setStatus(currentState.getNextForAbort());
Product asyncTempProduct = subscription.getAsyncTempProduct();
subscription.setAsyncTempProduct(null);
dataManager.remove(asyncTempProduct);
modUpgBean.deleteModifiedEntityForSubscription(subscription);
// send notify mail to administrators of the customer organization,
// subscription owner and technology provider organization
sendAbortAsyncModifySubscriptionEmail(subscription, organizationId,
reason);
}
void sendAbortAsyncModifySubscriptionEmail(Subscription subscription,
String organizationId, List<VOLocalizedText> reason) {
localizer.removeLocalizedValues(subscription.getKey(),
LocalizedObjectTypes.SUBSCRIPTION_MODIFICATION_REASON);
localizer.storeLocalizedResources(subscription.getKey(),
LocalizedObjectTypes.SUBSCRIPTION_MODIFICATION_REASON, reason);
dataManager.flush();
List<PlatformUser> receivers = manageBean
.getCustomerAndTechnicalProductAdminForSubscription(subscription);
for (PlatformUser platformUser : receivers) {
LocalizerFacade facade = new LocalizerFacade(localizer,
platformUser.getLocale());
String text = facade.getText(subscription.getKey(),
LocalizedObjectTypes.SUBSCRIPTION_MODIFICATION_REASON);
try {
commService.sendMail(platformUser,
EmailType.SUBSCRIPTION_PARAMETER_MODIFY_ABORT,
new Object[] { subscription.getSubscriptionId(),
organizationId, text },
subscription.getMarketplace());
} catch (MailOperationException e) {
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_MODIFY_PARAMETER_OF_SUBSCRIPTION_ABORT_CONFIRMING_FAILED);
}
}
}
@Override
public List<VOServiceOperationParameterValues> getServiceOperationParameterValues(
VOSubscription subscription, VOTechnicalServiceOperation operation)
throws ObjectNotFoundException, OperationNotPermittedException,
TechnicalServiceNotAliveException, ConcurrentModificationException,
TechnicalServiceOperationException {
ArgumentValidator.notNull("subscription", subscription);
ArgumentValidator.notNull("operation", operation);
Subscription sub = manageBean.loadSubscription(
subscription.getSubscriptionId(), 0);
TechnicalProductOperation op = dataManager.getReference(
TechnicalProductOperation.class, operation.getKey());
BaseAssembler.verifyVersionAndKey(sub, subscription);
BaseAssembler.verifyVersionAndKey(op, operation);
Map<String, List<String>> operationParameterValues = manageBean
.getOperationParameterValues(sub, op);
List<VOServiceOperationParameterValues> result = new LinkedList<>();
LocalizerFacade facade = new LocalizerFacade(localizer, dataManager
.getCurrentUser().getLocale());
for (Entry<String, List<String>> e : operationParameterValues
.entrySet()) {
OperationParameter param = op.findParameter(e.getKey());
if (param != null) {
VOServiceOperationParameterValues vo = TechServiceOperationParameterAssembler
.toVOServiceOperationParameterValues(param, facade,
e.getValue());
result.add(vo);
}
}
return result;
}
void updateInstanceInfoForCompletion(Subscription subscription,
VOInstanceInfo info) throws TechnicalServiceOperationException {
new SubscriptionInstanceInfo(localizer, subscription)
.validateAndUpdateInstanceInfoForCompletion(info);
}
@Override
@RolesAllowed("TECHNOLOGY_MANAGER")
public void updateAccessInformation(String subscriptionId,
String organizationId, VOInstanceInfo instance)
throws ObjectNotFoundException, SubscriptionStateException,
OperationNotPermittedException, ValidationException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("instance", instance);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
manageBean.validateTechnoloyProvider(subscription);
checkIPAddressChangedAndSendMailToUsers(subscription, instance);
updateInstanceInfo(subscription, instance);
}
void checkIPAddressChangedAndSendMailToUsers(Subscription subscription,
VOInstanceInfo instance) {
String currentAccessInfo = instance.getAccessInfo();
String lastAccessInfo = null;
if (isUsableAWSAccessInfo(currentAccessInfo)) {
List<String> accessInfos = getSubscriptionHistoryDao()
.getAccessInfos(subscription, instance);
for (String oldAccessInfo : accessInfos) {
if (isUsableAWSAccessInfo(oldAccessInfo)) {
lastAccessInfo = oldAccessInfo;
break;
}
}
if (checkIPAddressChanged(lastAccessInfo, currentAccessInfo)) {
sendMailForIPAddressChanged(subscription, currentAccessInfo);
}
}
}
boolean checkIPAddressChanged(String lastAccessInfo,
String currentAccessInfo) {
return (lastAccessInfo != null && !lastAccessInfo.isEmpty() && !lastAccessInfo
.equals(currentAccessInfo));
}
private void sendMailForIPAddressChanged(Subscription subscription,
String currentAccessInfo) {
List<UsageLicense> userLicenses = getUsageLicenseDao()
.getUsersforSubscription(subscription);
EmailType emailType = EmailType.SUBSCRIPTION_ACCESSINFO_CHANGED;
Long marketplaceKey = null;
if (subscription.getMarketplace() != null) {
marketplaceKey = Long.valueOf(subscription.getMarketplace()
.getKey());
}
SendMailPayload payload = new SendMailPayload();
for (UsageLicense usageLicense : userLicenses) {
payload.addMailObjectForUser(usageLicense.getUser().getKey(),
emailType, new Object[] { subscription.getSubscriptionId(),
getPublicDNS(currentAccessInfo),
getIPAddress(currentAccessInfo),
getKeyPairName(currentAccessInfo) }, marketplaceKey);
}
TaskMessage message = new TaskMessage(SendMailHandler.class, payload);
tqs.sendAllMessages(Collections.singletonList(message));
}
boolean isAWSAccessInfo(String accessInfo) {
try {
String subAccessInfo = accessInfo.substring(
accessInfo.indexOf(":"), accessInfo.indexOf(KEY_PAIR_NAME));
return subAccessInfo.contains(AMAZONAWS_COM);
} catch (StringIndexOutOfBoundsException e) {
return false;
}
}
boolean isUsableAWSAccessInfo(String accessInfo) {
return !(accessInfo == null || accessInfo.isEmpty())
&& isAWSAccessInfo(accessInfo)
&& !hasNullAccessInfo(accessInfo);
}
boolean hasNullAccessInfo(String accessInfo) {
return getPublicDNS(accessInfo).isEmpty()
|| getIPAddress(accessInfo).isEmpty()
|| getKeyPairName(accessInfo).isEmpty();
}
String getPublicDNS(String accessInfo) {
try {
return accessInfo.substring(0, accessInfo.indexOf(KEY_PAIR_NAME));
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
String getIPAddress(String accessInfo) {
try {
return accessInfo
.substring(accessInfo.indexOf("-"), accessInfo.indexOf("."))
.substring(1).replace('-', '.');
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
String getKeyPairName(String accessInfo) {
try {
return accessInfo.substring(accessInfo.indexOf(KEY_PAIR_NAME),
accessInfo.length());
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
void updateInstanceInfo(Subscription subscription, VOInstanceInfo info)
throws ValidationException {
new SubscriptionInstanceInfo(localizer, subscription)
.validateAndUpdateInstanceInfo(info);
}
/**
* Save udas for asynchronously modify or upgrade subscription. Store uda
* value in modifieduda temporarily.
*
* @param udas
* The list of VOUda with new value.
* @param dbSubscription
* The subscription to be modified or upgraded.
*/
void saveUdasForAsyncModifyOrUpgradeSubscription(List<VOUda> udas,
Subscription dbSubscription) throws MandatoryUdaMissingException,
ValidationException, NonUniqueBusinessKeyException,
ObjectNotFoundException, OperationNotPermittedException,
ConcurrentModificationException {
Organization supplier = dbSubscription.getProduct()
.getSupplierOrResellerTemplate().getVendor();
manageBean.getUdaAccess().validateUdaAndAdaptTargetKey(udas, supplier,
dbSubscription);
List<VOUda> newUdas = new ArrayList<>();
List<VOUda> defaultValueUdas = new ArrayList<>();
for (VOUda voUda : udas) {
if (voUda.getKey() > 0) {
modUpgBean.storeModifiedUda(voUda.getKey(),
ModifiedEntityType.UDA_VALUE, voUda.getUdaValue(),
dbSubscription.getKey());
} else {
newUdas.add(voUda);
}
}
for (VOUda voUda : newUdas) {
VOUda defaultValueUda = new VOUda();
defaultValueUda.setTargetObjectKey(voUda.getTargetObjectKey());
defaultValueUda.setUdaDefinition(voUda.getUdaDefinition());
defaultValueUda.setUdaValue(voUda.getUdaDefinition()
.getDefaultValue());
defaultValueUdas.add(defaultValueUda);
}
manageBean.getUdaAccess().saveUdas(defaultValueUdas,
dbSubscription.getOrganization());
for (VOUda voUda : newUdas) {
Uda uda = new Uda();
uda.setTargetObjectKey(voUda.getTargetObjectKey());
uda.setUdaDefinitionKey(voUda.getUdaDefinition().getKey());
uda = (Uda) dataManager.getReferenceByBusinessKey(uda);
modUpgBean.storeModifiedUda(uda.getKey(),
ModifiedEntityType.UDA_VALUE, voUda.getUdaValue(),
dbSubscription.getKey());
}
}
public SubscriptionHistoryDao getSubscriptionHistoryDao() {
return new SubscriptionHistoryDao(dataManager);
}
public UsageLicenseDao getUsageLicenseDao() {
return new UsageLicenseDao(dataManager);
}
public SubscriptionDao getSubscriptionDao() {
return new SubscriptionDao(dataManager);
}
public MarketplaceDao getMarketplaceDao() {
return new MarketplaceDao(dataManager);
}
public ModifiedEntityDao getModifiedEntityDao() {
return new ModifiedEntityDao(dataManager);
}
public OrganizationDao getOrganizationDao() {
return new OrganizationDao(dataManager);
}
public ProductDao getProductDao() {
return new ProductDao(dataManager);
}
public SessionDao getSessionDao() {
return new SessionDao(dataManager);
}
@Override
@RolesAllowed({ "TECHNOLOGY_MANAGER" })
public void updateAsyncOperationProgress(String transactionId,
OperationStatus status, List<VOLocalizedText> progress)
throws OperationNotPermittedException, OperationStateException {
ArgumentValidator.notNull("transactionId", transactionId);
ArgumentValidator.notNull("status", status);
operationRecordBean.updateOperationStatus(transactionId, status,
progress);
}
@Override
@RolesAllowed({ "TECHNOLOGY_MANAGER" })
public void updateAsyncSubscriptionStatus(String subscriptionId,
String organizationId, VOInstanceInfo instanceInfo)
throws ObjectNotFoundException {
ArgumentValidator.notNull("subscriptionId", subscriptionId);
ArgumentValidator.notNull("organizationId", organizationId);
ArgumentValidator.notNull("instance", instanceInfo);
Subscription subscription = manageBean.findSubscription(subscriptionId,
organizationId);
subscription.setStatus(SubscriptionStatus.PENDING);
List<PlatformUser> receivers = manageBean
.getCustomerAdminsAndSubscriptionOwner(subscription);
for (PlatformUser platformUser : receivers) {
try {
commService.sendMail(
platformUser,
EmailType.SUBSCRIPTION_INSTANCE_NOT_FOUND,
new Object[] { subscriptionId,
instanceInfo.getInstanceId() },
subscription.getMarketplace());
} catch (MailOperationException e) {
// only log the exception and proceed
LOG.logWarn(
Log4jLogger.SYSTEM_LOG,
e,
LogMessageIdentifier.WARN_MODIFY_PARAMETER_OF_SUBSCRIPTION_CONFIRMING_FAILED);
}
}
}
@TransactionAttribute(TransactionAttributeType.MANDATORY)
private List<Subscription> getSubscriptionsForUserInt(PlatformUser user,
Pagination pagination) {
return getSubscriptionDao().getSubscriptionsForUser(user, pagination);
}
@Override
public List<Subscription> getSubscriptionsForCurrentUser(
Pagination pagination) {
PlatformUser user = dataManager.getCurrentUser();
return getSubscriptionsForUserInt(user, pagination);
}
@Override
public UsageLicense getSubscriptionUsageLicense(PlatformUser user,
Long subKey) {
return getSubscriptionDao().getUserLicense(user,
subKey == null ? -1 : subKey.longValue());
}
@Override
public void removeSubscriptionOwner(Subscription sub) {
sub.setOwner(null);
dataManager.merge(sub);
}
@Override
public Subscription getMySubscriptionDetails(long key) {
return getSubscriptionDao().getMySubscriptionDetails(key);
}
}
| Removed manual setting of UUID during subscription - Paulina Badziak [2,0,0]
| oscm-subscriptionmgmt/javasrc/org/oscm/subscriptionservice/bean/SubscriptionServiceBean.java | Removed manual setting of UUID during subscription - Paulina Badziak [2,0,0] | <ide><path>scm-subscriptionmgmt/javasrc/org/oscm/subscriptionservice/bean/SubscriptionServiceBean.java
<ide> theProduct.setOwningSubscription(null);
<ide> // subscription copies do not have/need a CatalogEntry
<ide> theProduct.setCatalogEntries(new ArrayList<CatalogEntry>());
<del> theProduct.getPriceModel().setUuid(productTemplate.getPriceModel().getUuid());
<add>
<ide> try {
<ide> dataManager.persist(theProduct);
<ide> } catch (NonUniqueBusinessKeyException e) { |
|
JavaScript | apache-2.0 | 84c34cdcda00547285126c5c06ac51ed90c38f2a | 0 | proxiemind/MultiOgar-Edited,proxiemind/MultiOgar-Edited,proxiemind/MultiOgar-Edited,Barbosik/MultiOgar,Barbosik/MultiOgar | var Mode = require('./Mode');
function Teams() {
Mode.apply(this, Array.prototype.slice.call(arguments));
this.ID = 0;
this.name = "Teams";
this.decayMod = 1.5;
this.packetLB = 50;
this.haveTeams = true;
this.colorFuzziness = 32;
// Special
this.teamAmount = 3; // Amount of teams. Having more than 3 teams will cause the leaderboard to work incorrectly (client issue).
this.colors = [
{'r': 223, 'g': 0, 'b': 0},
{'r': 0, 'g': 223, 'b': 0},
{'r': 0, 'g': 0, 'b': 223},
]; // Make sure you add extra colors here if you wish to increase the team amount [Default colors are: Red, Green, Blue]
this.nodes = []; // Teams
}
module.exports = Teams;
Teams.prototype = new Mode();
//Gamemode Specific Functions
Teams.prototype.fuzzColorComponent = function(component) {
component += Math.random() * this.colorFuzziness >> 0;
return component;
};
Teams.prototype.getTeamColor = function(team) {
var color = this.colors[team];
return {
r: this.fuzzColorComponent(color.r),
b: this.fuzzColorComponent(color.b),
g: this.fuzzColorComponent(color.g)
};
};
// Override
Teams.prototype.onPlayerSpawn = function(gameServer,player) {
// Random color based on team
player.color = this.getTeamColor(player.team);
// Spawn player
gameServer.spawnPlayer(player);
};
Teams.prototype.onServerInit = function(gameServer) {
// Set up teams
for (var i = 0; i < this.teamAmount; i++) {
this.nodes[i] = [];
}
};
Teams.prototype.onPlayerInit = function(player) {
// Get random team
player.team = Math.floor(Math.random() * this.teamAmount);
};
Teams.prototype.onCellAdd = function(cell) {
// Add to team list
this.nodes[cell.owner.getTeam()].push(cell);
};
Teams.prototype.onCellRemove = function(cell) {
// Remove from team list
var index = this.nodes[cell.owner.getTeam()].indexOf(cell);
if (index != -1) {
this.nodes[cell.owner.getTeam()].splice(index, 1);
}
};
Teams.prototype.updateLB = function(gameServer) {
var total = 0;
var teamMass = [];
// Get mass
for (var i = 0; i < this.teamAmount; i++) {
// Set starting mass
teamMass[i] = 0;
// Loop through cells
for (var j = 0; j < this.nodes[i].length;j++) {
var cell = this.nodes[i][j];
if (!cell) {
continue;
}
teamMass[i] += cell.mass;
total += cell.mass;
}
}
// Calc percentage
for (var i = 0; i < this.teamAmount; i++) {
// No players
if (total <= 0) {
continue;
}
gameServer.leaderboard[i] = teamMass[i]/total;
}
};
| src/gamemodes/Teams.js | var Mode = require('./Mode');
function Teams() {
Mode.apply(this, Array.prototype.slice.call(arguments));
this.ID = 0;
this.name = "Teams";
this.decayMod = 1.5;
this.packetLB = 50;
this.haveTeams = true;
this.colorFuzziness = 32;
// Special
this.teamAmount = 3; // Amount of teams. Having more than 3 teams will cause the leaderboard to work incorrectly (client issue).
this.colors = [
{'r':255 - this.colorFuzziness, 'g': 0 + this.colorFuzziness, 'b': 0 + this.colorFuzziness},
{'r': 0 + this.colorFuzziness, 'g':255 - this.colorFuzziness, 'b': 0 + this.colorFuzziness},
{'r': 0 + this.colorFuzziness, 'g': 0 + this.colorFuzziness, 'b':255 - this.colorFuzziness},
]; // Make sure you add extra colors here if you wish to increase the team amount [Default colors are: Red, Green, Blue]
this.nodes = []; // Teams
}
module.exports = Teams;
Teams.prototype = new Mode();
//Gamemode Specific Functions
Teams.prototype.fuzzColorComponent = function(component, amount) {
component += Math.floor(Math.random() * (amount * 2 + 1)) - amount;
return component < 0 ? 0 : component > 255 ? 255 : component;
};
Teams.prototype.fuzzColor = function(color, amount) {
return {
r: this.fuzzColorComponent(color.r, amount),
b: this.fuzzColorComponent(color.b, amount),
g: this.fuzzColorComponent(color.g, amount)
};
};
Teams.prototype.getTeamColor = function(team) {
return this.fuzzColor(this.colors[team], this.colorFuzziness);
};
// Override
Teams.prototype.onServerInit = function(gameServer) {
// Set up teams
for (var i = 0; i < this.teamAmount; i++) {
this.nodes[i] = [];
}
};
Teams.prototype.onPlayerInit = function(player) {
// Get random team
player.team = Math.floor(Math.random() * this.teamAmount);
player.color = this.getTeamColor(player.team);
};
Teams.prototype.onCellAdd = function(cell) {
// Add to team list
this.nodes[cell.owner.getTeam()].push(cell);
};
Teams.prototype.onCellRemove = function(cell) {
// Remove from team list
var index = this.nodes[cell.owner.getTeam()].indexOf(cell);
if (index != -1) {
this.nodes[cell.owner.getTeam()].splice(index, 1);
}
};
Teams.prototype.updateLB = function(gameServer) {
var total = 0;
var teamMass = [];
// Get mass
for (var i = 0; i < this.teamAmount; i++) {
// Set starting mass
teamMass[i] = 0;
// Loop through cells
for (var j = 0; j < this.nodes[i].length;j++) {
var cell = this.nodes[i][j];
if (!cell) {
continue;
}
teamMass[i] += cell.mass;
total += cell.mass;
}
}
// Calc percentage
for (var i = 0; i < this.teamAmount; i++) {
// No players
if (total <= 0) {
continue;
}
gameServer.leaderboard[i] = teamMass[i]/total;
}
};
| Simplify code
| src/gamemodes/Teams.js | Simplify code | <ide><path>rc/gamemodes/Teams.js
<ide> // Special
<ide> this.teamAmount = 3; // Amount of teams. Having more than 3 teams will cause the leaderboard to work incorrectly (client issue).
<ide> this.colors = [
<del> {'r':255 - this.colorFuzziness, 'g': 0 + this.colorFuzziness, 'b': 0 + this.colorFuzziness},
<del> {'r': 0 + this.colorFuzziness, 'g':255 - this.colorFuzziness, 'b': 0 + this.colorFuzziness},
<del> {'r': 0 + this.colorFuzziness, 'g': 0 + this.colorFuzziness, 'b':255 - this.colorFuzziness},
<add> {'r': 223, 'g': 0, 'b': 0},
<add> {'r': 0, 'g': 223, 'b': 0},
<add> {'r': 0, 'g': 0, 'b': 223},
<ide> ]; // Make sure you add extra colors here if you wish to increase the team amount [Default colors are: Red, Green, Blue]
<ide> this.nodes = []; // Teams
<ide> }
<ide>
<ide> //Gamemode Specific Functions
<ide>
<del>Teams.prototype.fuzzColorComponent = function(component, amount) {
<del> component += Math.floor(Math.random() * (amount * 2 + 1)) - amount;
<del> return component < 0 ? 0 : component > 255 ? 255 : component;
<add>Teams.prototype.fuzzColorComponent = function(component) {
<add> component += Math.random() * this.colorFuzziness >> 0;
<add> return component;
<ide> };
<ide>
<del>Teams.prototype.fuzzColor = function(color, amount) {
<add>Teams.prototype.getTeamColor = function(team) {
<add> var color = this.colors[team];
<ide> return {
<del> r: this.fuzzColorComponent(color.r, amount),
<del> b: this.fuzzColorComponent(color.b, amount),
<del> g: this.fuzzColorComponent(color.g, amount)
<add> r: this.fuzzColorComponent(color.r),
<add> b: this.fuzzColorComponent(color.b),
<add> g: this.fuzzColorComponent(color.g)
<ide> };
<ide> };
<ide>
<del>Teams.prototype.getTeamColor = function(team) {
<del> return this.fuzzColor(this.colors[team], this.colorFuzziness);
<add>// Override
<add>
<add>Teams.prototype.onPlayerSpawn = function(gameServer,player) {
<add> // Random color based on team
<add> player.color = this.getTeamColor(player.team);
<add> // Spawn player
<add> gameServer.spawnPlayer(player);
<ide> };
<del>
<del>// Override
<ide>
<ide> Teams.prototype.onServerInit = function(gameServer) {
<ide> // Set up teams
<ide> Teams.prototype.onPlayerInit = function(player) {
<ide> // Get random team
<ide> player.team = Math.floor(Math.random() * this.teamAmount);
<del> player.color = this.getTeamColor(player.team);
<ide> };
<ide>
<ide> Teams.prototype.onCellAdd = function(cell) { |
|
Java | apache-2.0 | 7c3dfd35504f68b93a555962c6799546a94f35c7 | 0 | MarkGartner/mgas | package ru.job4j.array;
public class RotateArray
{
public int[][] rotate(int[][] array)
{
int x = array.length;
int[][] rotatedArray = new int[x][x];
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
rotatedArray[j][x-1-i] = array[i][j];
}
}
return rotatedArray;
}
}
| chapter_001/src/main/java/ru/job4j/array/RotateArray.java | package ru.job4j.array;
public class RotateArray
{
public int[][] rotate(int[][] array)
{
int x = array.length;
int[][] rotatedArray = new int[x][x];
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
rotatedArray[j][x-1-i] = array[i][j];
}
}
return rotatedArray;
}
public static void main(String[] args)
{
int n = 3;
int[][] arr = new int[n][n];
int inc=1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
arr[i][j]=inc;
inc++;
}
}
RotateArray sample = new RotateArray();
int [][] rot = sample.rotate(arr);
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.println(rot[i][j]);
}
}
}
}
| added 2d array twist + test
| chapter_001/src/main/java/ru/job4j/array/RotateArray.java | added 2d array twist + test | <ide><path>hapter_001/src/main/java/ru/job4j/array/RotateArray.java
<ide>
<ide> return rotatedArray;
<ide> }
<del>
<del> public static void main(String[] args)
<del> {
<del> int n = 3;
<del> int[][] arr = new int[n][n];
<del> int inc=1;
<del> for(int i=0;i<n;i++)
<del> {
<del> for(int j=0;j<n;j++)
<del> {
<del> arr[i][j]=inc;
<del> inc++;
<del> }
<del> }
<del>
<del> RotateArray sample = new RotateArray();
<del> int [][] rot = sample.rotate(arr);
<del>
<del> for(int i=0;i<n;i++)
<del> {
<del> for(int j=0;j<n;j++)
<del> {
<del> System.out.println(rot[i][j]);
<del> }
<del> }
<del>
<del> }
<ide> } |
|
JavaScript | mit | 327cd612a1d6858f5a8ebe0af961fe1815f7c530 | 0 | phetsims/sun,phetsims/sun,phetsims/sun | // Copyright 2002-2013, University of Colorado Boulder
/**
* A rectangular button.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
define( function( require ) {
'use strict';
// imports
var Button = require( 'SUN/Button' ); //TODO use SUN/Button
var inherit = require( 'PHET_CORE/inherit' );
var Node = require( 'SCENERY/nodes/Node' );
var Rectangle = require( 'SCENERY/nodes/Rectangle' );
/**
* @param {Node} content
* @param {Function} callback
* @param options
* @constructor
*/
function RectangleButton( content, callback, options ) {
options = _.extend( {
fill: 'white',
disabledFill: 'rgb(210,210,210)',
stroke: 'black',
disabledStroke: 'rgb(175,175,175)',
lineWidth: 1,
//TODO default margins and corner radius should be computed based on content dimensions
xMargin: 5,
yMargin: 5,
cornerRadius: 10
},
options );
var thisButton = this;
// parent for content + rectangle
var node = new Node();
// rectangle around the content
var rectangle = new Rectangle(
0, 0, content.width + ( 2 * options.xMargin ), content.height + ( 2 * options.yMargin ), options.cornerRadius, options.cornerRadius,
{ lineWidth: options.lineWidth } );
node.addChild( rectangle );
// content centered in the rectangle
content.centerX = rectangle.width / 2;
content.centerY = rectangle.height / 2;
node.addChild( content );
Button.call( thisButton, node, callback );
// enable/disable the pieces that are specific to this subtype
thisButton._enabled.link( function( enabled ) {
rectangle.fill = enabled ? options.fill : options.disabledFill;
rectangle.stroke = enabled ? options.stroke : options.disabledStroke;
} );
thisButton.mutate( options );
}
inherit( Button, RectangleButton );
return RectangleButton;
} );
| js/RectangleButton.js | // Copyright 2002-2013, University of Colorado Boulder
/**
* A rectangular button.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
define( function( require ) {
// imports
var Button = require( 'SUN/Button' ); //TODO use SUN/Button
var inherit = require( 'PHET_CORE/inherit' );
var Node = require( 'SCENERY/nodes/Node' );
var Rectangle = require( 'SCENERY/nodes/Rectangle' );
/**
* @param {Node} content
* @param {Function} callback
* @param options
* @constructor
*/
function RectangleButton( content, callback, options ) {
options = _.extend( {
fill: 'white',
disabledFill: 'rgb(210,210,210)',
stroke: 'black',
disabledStroke: 'rgb(175,175,175)',
lineWidth: 1,
//TODO default margins and corner radius should be computed based on content dimensions
xMargin: 5,
yMargin: 5,
cornerRadius: 10
},
options );
var thisButton = this;
// parent for content + rectangle
var node = new Node();
// rectangle around the content
var rectangle = new Rectangle(
0, 0, content.width + ( 2 * options.xMargin ), content.height + ( 2 * options.yMargin ), options.cornerRadius, options.cornerRadius,
{ lineWidth: options.lineWidth } );
node.addChild( rectangle );
// content centered in the rectangle
content.centerX = rectangle.width / 2;
content.centerY = rectangle.height / 2;
node.addChild( content );
Button.call( thisButton, node, callback );
// enable/disable the pieces that are specific to this subtype
thisButton._enabled.link( function( enabled ) {
rectangle.fill = enabled ? options.fill : options.disabledFill;
rectangle.stroke = enabled ? options.stroke : options.disabledStroke;
} );
thisButton.mutate( options );
}
inherit( Button, RectangleButton );
return RectangleButton;
} );
| use strict
| js/RectangleButton.js | use strict | <ide><path>s/RectangleButton.js
<ide> * @author Chris Malley (PixelZoom, Inc.)
<ide> */
<ide> define( function( require ) {
<add> 'use strict';
<ide>
<ide> // imports
<ide> var Button = require( 'SUN/Button' ); //TODO use SUN/Button |
|
JavaScript | mit | 861d4f9f3ae4c36868b3585d40bc5eab928e65b0 | 0 | 3ventic/tmi-irc-relay | var net = require('net');
var Message = require("irc-message").parseMessage;
var IRCMessage = require("irc-message").IRCMessage;
var lstream = require("lstream");
var request = require("request");
var messageTools = new IRCMessage();
var slowTopic = {};
var subTopic = {};
var server = net.createServer(function(socket) {
socket.messageStream = new lstream;
socket.outgoingMessageStream = new lstream;
socket.channels = {};
socket.irc = new net.Socket();
socket.irc.connect(6667, 'irc.twitch.tv');
socket.irc.pipe(socket.messageStream);
socket.messageStream.on('data', function(data) {
parseIncoming(socket, data);
});
socket.on('close', function() {
Object.keys(socket.channels).forEach(function(channel) {
clearInterval(socket.channels[channel].timer);
});
socket.irc.destroy();
socket.destroy();
delete socket;
});
socket.outgoingMessageStream.on('data', function(data) {
parseOutgoing(socket, data);
});
socket.pipe(socket.outgoingMessageStream);
});
function parseIncoming(socket, data) {
var message = Message(data);
if(message.command === 'MODE') {
return;
}
if(message.prefix === '[email protected]' || message.prefix === 'jtv') {
var channel = message.params[0];
var jtvData = message.params[1].split(' ');
if(channel === socket.nick || !socket.channels[channel]) return;
if(!(channel in slowTopic)) slowTopic[channel] = '';
if(!(channel in subTopic)) subTopic[channel] = '';
var userList = socket.channels[channel].users;
var subscribers = /^This room is (now|no longer) in subscribers-only mode\.$/.test(message.params[1]);
var slowMode = /^This room is (now|no longer) in slow mode\./.test(message.params[1]);
if(jtvData[0] === 'HOSTTARGET') {
if (jtvData[1] !== '-') {
socket.write(':Twitch NOTICE '+channel+' :Now hosting '+jtvData[1]+' with '+jtvData[2]+' viewers\r\n');
}
}
else if(jtvData[0] === 'SPECIALUSER') {
var user = jtvData[1];
if(!userList[user]) {
userList[user] = {
owner: false,
moderator: false,
turbo: false,
subscriber: false,
admin: false,
staff: false
}
socket.write(':'+user+'!'+user+'@'+user+'.tmi.twitch.tv JOIN '+channel+'\r\n');
}
if(channel.replace('#','') === user && !userList[user].owner) {
userList[user].owner = true;
userList[user].moderator = true;
socket.write(':Twitch MODE '+channel+' +o '+user+' '+user+'\r\n');
}
if(jtvData[2] === 'staff' && !userList[user].staff) {
userList[user].staff = true;
userList[user].moderator = true;
socket.write(':Twitch MODE '+channel+' +qo '+user+'\r\n');
}
if(jtvData[2] === 'admin' && !userList[user].staff) {
userList[user].admin = true;
userList[user].moderator = true;
socket.write(':Twitch MODE '+channel+' +ao '+user+'\r\n');
}
if(jtvData[2] === 'subscriber' && !userList[user].subscriber) {
userList[user].subscriber = true;
socket.write(':Twitch MODE '+channel+' +h '+user+'\r\n');
}
if(jtvData[2] === 'turbo' && !userList[user].turbo) {
userList[user].turbo = true;
socket.write(':Twitch MODE '+channel+' +v '+user+'\r\n');
}
}
else if(subscribers) {
if(message.params[1].indexOf('now') !== -1) {
subTopic[channel] = ' | Subscribers-only enabled';
socket.write(':Twitch MODE '+channel+' +m\r\n');
socket.write(':Twitch TOPIC '+channel+' '+slowTopic[channel]+subTopic[channel]+'\r\n');
} else {
subTopic[channel] = '';
socket.write(':Twitch MODE '+channel+' -m\r\n');
socket.write(':Twitch TOPIC '+channel+' '+slowTopic[channel]+subTopic[channel]+'\r\n');
}
}
else if(slowMode) {
if(message.params[1].indexOf('now') !== -1) {
var slowTime = /You may send messages every ([0-9]+) seconds/.exec(message.params[1]);
slowTopic[channel] = 'Slow mode is '+slowTime[1].trim()+' seconds';
socket.write(':Twitch MODE '+channel+' +f '+slowTime[1].trim()+'s\r\n');
socket.write(':Twitch TOPIC '+channel+' '+slowTopic[channel]+subTopic[channel]+'\r\n');
} else {
slowTopic[channel] = 'Slow mode is disabled';
socket.write(':Twitch MODE '+channel+' -f\r\n');
socket.write(':Twitch TOPIC '+channel+' '+slowTopic[channel]+subTopic[channel]+'\r\n');
}
}
else if(jtvData[0] === 'CLEARCHAT') {
socket.write(':Twitch NOTICE '+channel+' :'+jtvData[1]+' has been timed out or banned\r\n');
}
else if(jtvData[0].match(/(?:Now|USERCOLOR|EMOTESET)/)) {
return;
}
else {
var params = '';
var length = message.params.length;
for (var i = 1; i < length; i++) {
params += ' ' + message.params[i];
}
params = params.trim();
socket.write(':Twitch NOTICE '+channel+' :'+params+'\r\n');
}
return;
}
socket.write(data+'\r\n');
}
function parseOutgoing(socket, data) {
var message = Message(data);
if(message.command === 'NICK') {
socket.nick = message.params[0].trim();
socket.irc.write('TWITCHCLIENT 3'+'\r\n');
socket.write(':tmi.twitch.tv 005 '+socket.nick+' PREFIX=(qaohv)~&@$+ CHANTYPES=# NETWORK=Twitch :are supported by this server\r\n');
}
else if(message.command === 'JOIN') {
message.params[0].split(',').forEach(function(channel) {
socket.channels[channel] = {
users: {},
topic: 'Welcome to the channel!',
timer: setInterval(function() { socket.channels[channel].update() }, 20000),
update: function() {
request.get({
url: 'https://tmi.twitch.tv/group/user/'+channel.replace('#','')+'/chatters',
json: true
}, function(err, res, data) {
var userList = socket.channels[channel].users;
if(data.chatters) {
var currentUsers = Object.keys(userList);
var newUsers = [];
var chatterTypes = Object.keys(data.chatters);
for(var i=0; i<chatterTypes.length; i++) {
newUsers = newUsers.concat(data.chatters[chatterTypes[i]]);
}
var joins = [];
var parts = [];
var modes = [];
currentUsers.forEach(function(user) {
if(newUsers.indexOf(user) === -1 && socket.nick !== user) {
delete userList[user];
parts.push(user);
}
});
for(var i=0; i<chatterTypes.length; i++) {
data.chatters[chatterTypes[i]].forEach(function(user) {
if(!userList[user]) {
userList[user] = {
owner: false,
moderator: false,
turbo: false,
subscriber: false,
admin: false,
staff: false
}
joins.push(user);
}
if(channel.replace('#','') === user && !userList[user].owner) {
userList[user].owner = true;
modes.push('+o '+user);
}
if(chatterTypes[i] === 'moderators' && !userList[user].moderator) {
userList[user].moderator = true;
modes.push('+o '+user);
} else if(chatterTypes[i] === 'viewers' && userList[user].moderator && data.chatters['moderators'].length > 0) {
userList[user].moderator = false;
modes.push('-o '+user);
}
if(chatterTypes[i] === 'staff' && !userList[user].staff) {
userList[user].staff = true;
modes.push('+qo '+user);
}
if(chatterTypes[i] === 'admins' && !userList[user].admin) {
userList[user].admin = true;
modes.push('+ao '+user);
}
});
}
if(joins.length < 100) {
while(joins.length) {
var user = joins.splice(0, 1).toString();
socket.write(':'+user+'!'+user+'@'+user+'.tmi.twitch.tv JOIN '+channel+'\r\n');
}
while(parts.length) {
var user = parts.splice(0, 1).toString();
socket.write(':'+user+'!'+user+'@'+user+'.tmi.twitch.tv PART '+channel+'\r\n');
}
} else {
while(newUsers.length) {
var users = newUsers.splice(0, 15).join(' ');
socket.write(':tmi.twitch.tv 353 '+socket.nick+' = '+channel+' :'+users+'\r\n');
}
socket.write(':tmi.twitch.tv 366 '+socket.nick+' '+channel+' :End of /NAMES list\r\n');
}
while(modes.length) {
var mode = modes.splice(0, 1).toString();
socket.write(':Twitch MODE '+channel+' '+mode+'\r\n');
}
}
})
}
}
socket.channels[channel].update();
});
}
else if(message.command === 'PART') {
message.params[0].split(',').forEach(function(channel) {
if(socket.channels[channel]) {
clearInterval(socket.channels[channel].timer);
delete socket.channels[channel];
}
});
}
else if(message.command === 'ISON') {
socket.write(':tmi.twitch.tv 303 '+socket.nick+' :'+message.params.join(' ')+'\r\n');
return;
}
else if(message.command.toUpperCase() === 'SLOW') {
if(!message.params[1]) message.params[1] = '120';
socket.irc.write(':tmi.twitch.tv PRIVMSG '+message.params[0]+' :/slow '+message.params[1].trim()+'\r\n');
return;
}
else if(message.command === 'KICK' || message.command.toUpperCase() === 'TIMEOUT') {
if(!message.params[2]) message.params[2] = '600';
socket.irc.write(':tmi.twitch.tv PRIVMSG '+message.params[0]+' :/timeout '+message.params[1].trim()+' '+message.params[2].trim()+'\r\n');
socket.write(':Twitch NOTICE '+message.params[0]+' :You have timed out '+message.params[1].trim()+' for '+message.params[2]+' seconds.'+'\r\n');
return;
}
else if(message.command.match(/^(?:un)?ban$/i)) {
socket.irc.write(':tmi.twitch.tv PRIVMSG '+message.params[0]+' :/'+message.command.toLowerCase()+' '+message.params[1].trim()+'\r\n');
socket.write(':Twitch NOTICE '+message.params[0]+' :You have '+message.command.toLowerCase()+'ned '+message.params[1].trim()+'\r\n');
return;
}
else if(message.command === 'MODE') {
if(message.params[1] === '+b' || message.params[1] === '-b') {
if(!message.params[2]) return;
if(messageTools.prefixIsHostmask(message.params[2])) {
var hostmask = messageTools.parseHostmaskFromPrefix(message.params[2]);
var user;
if(hostmask.nickname && hostmask.nickname !== '*') {
user = hostmask.nickname;
} else if(hostmask.username && hostmask.username !== '*') {
user = hostmask.username;
} else if(hostmask.hostname && hostmask.hostname !== '*') {
user = hostmask.hostname.split('.')[0];
} else {
user = socket.nick;
}
} else {
var user = message.params[2];
}
var command = (message.params[1] === '+b') ? 'ban' : 'unban';
socket.irc.write(':tmi.twitch.tv PRIVMSG '+message.params[0]+' :/'+command+' '+user+'\r\n');
socket.write(':Twitch NOTICE '+message.params[0]+' :You have '+command+'ned '+user+'.\r\n');
}
return;
}
else if(message.command === 'WHO') {
socket.write(':tmi.twitch.tv 315 '+socket.nick+' '+message.params[0]+' :End of /WHO list.'+'\r\n');
return;
}
else {
var params = '';
var length = message.params.length;
for (var i = 1; i < length; i++) {
params += ' ' + message.params[i];
}
params = params.trim();
socket.irc.write(':tmi.twitch.tv PRIVMSG '+message.params[0]+' :/'+message.command.toLowerCase()+' '+params+'\r\n');
}
socket.irc.write(data+'\r\n');
}
server.listen(6969);
| index.js | var net = require('net');
var Message = require("irc-message").parseMessage;
var IRCMessage = require("irc-message").IRCMessage;
var lstream = require("lstream");
var request = require("request");
var messageTools = new IRCMessage();
var slowTopic = {};
var subTopic = {};
var server = net.createServer(function(socket) {
socket.messageStream = new lstream;
socket.outgoingMessageStream = new lstream;
socket.channels = {};
socket.irc = new net.Socket();
socket.irc.connect(6667, 'irc.twitch.tv');
socket.irc.pipe(socket.messageStream);
socket.messageStream.on('data', function(data) {
parseIncoming(socket, data);
});
socket.on('close', function() {
Object.keys(socket.channels).forEach(function(channel) {
clearInterval(socket.channels[channel].timer);
});
socket.irc.destroy();
socket.destroy();
delete socket;
});
socket.outgoingMessageStream.on('data', function(data) {
parseOutgoing(socket, data);
});
socket.pipe(socket.outgoingMessageStream);
});
function parseIncoming(socket, data) {
var message = Message(data);
if(message.command === 'MODE') {
return;
}
if(message.prefix === '[email protected]' || message.prefix === 'jtv') {
var channel = message.params[0];
var jtvData = message.params[1].split(' ');
if(channel === socket.nick || !socket.channels[channel]) return;
if(!(channel in slowTopic)) slowTopic[channel] = '';
if(!(channel in subTopic)) subTopic[channel] = '';
var userList = socket.channels[channel].users;
var subscribers = /^This room is (now|no longer) in subscribers-only mode\.$/.test(message.params[1]);
var slowMode = /^This room is (now|no longer) in slow mode\./.test(message.params[1]);
if(jtvData[0] === 'HOSTTARGET') {
if (jtvData[1] !== '-') {
socket.write(':Twitch NOTICE '+channel+' :Now hosting '+jtvData[1]+' with '+jtvData[2]+' viewers\r\n');
}
}
else if(jtvData[0] === 'SPECIALUSER') {
var user = jtvData[1];
if(!userList[user]) {
userList[user] = {
owner: false,
moderator: false,
turbo: false,
subscriber: false,
admin: false,
staff: false
}
socket.write(':'+user+'!'+user+'@'+user+'.tmi.twitch.tv JOIN '+channel+'\r\n');
}
if(channel.replace('#','') === user && !userList[user].owner) {
userList[user].owner = true;
userList[user].moderator = true;
socket.write(':Twitch MODE '+channel+' +o '+user+' '+user+'\r\n');
}
if(jtvData[2] === 'staff' && !userList[user].staff) {
userList[user].staff = true;
userList[user].moderator = true;
socket.write(':Twitch MODE '+channel+' +qo '+user+'\r\n');
}
if(jtvData[2] === 'admin' && !userList[user].staff) {
userList[user].admin = true;
userList[user].moderator = true;
socket.write(':Twitch MODE '+channel+' +ao '+user+'\r\n');
}
if(jtvData[2] === 'subscriber' && !userList[user].subscriber) {
userList[user].subscriber = true;
socket.write(':Twitch MODE '+channel+' +h '+user+'\r\n');
}
if(jtvData[2] === 'turbo' && !userList[user].turbo) {
userList[user].turbo = true;
socket.write(':Twitch MODE '+channel+' +v '+user+'\r\n');
}
}
else if(subscribers) {
if(message.params[1].indexOf('now') !== -1) {
subTopic[channel] = ' | Subscribers-only enabled';
socket.write(':Twitch MODE '+channel+' +m\r\n');
socket.write(':Twitch TOPIC '+channel+' '+slowTopic[channel]+subTopic[channel]+'\r\n');
} else {
subTopic[channel] = '';
socket.write(':Twitch MODE '+channel+' -m\r\n');
socket.write(':Twitch TOPIC '+channel+' '+slowTopic[channel]+subTopic[channel]+'\r\n');
}
}
else if(slowMode) {
if(message.params[1].indexOf('now') !== -1) {
var slowTime = /You may send messages every ([0-9]+) seconds/.exec(message.params[1]);
slowTopic[channel] = 'Slow mode is '+slowTime[1].trim()+' seconds';
socket.write(':Twitch MODE '+channel+' +f '+slowTime[1].trim()+'s\r\n');
socket.write(':Twitch TOPIC '+channel+' '+slowTopic[channel]+subTopic[channel]+'\r\n');
} else {
slowTopic[channel] = 'Slow mode is disabled';
socket.write(':Twitch MODE '+channel+' -f\r\n');
socket.write(':Twitch TOPIC '+channel+' '+slowTopic[channel]+subTopic[channel]+'\r\n');
}
}
else if(jtvData[0].match(/(?:Now|USERCOLOR|EMOTESET)/)) {
return;
}
else {
var params = '';
var length = message.params.length;
for (var i = 1; i < length; i++) {
params += ' ' + message.params[i];
}
params = params.trim();
socket.write(':Twitch NOTICE '+channel+' :'+params+'\r\n');
}
return;
}
socket.write(data+'\r\n');
}
function parseOutgoing(socket, data) {
var message = Message(data);
if(message.command === 'NICK') {
socket.nick = message.params[0].trim();
socket.irc.write('TWITCHCLIENT 3'+'\r\n');
socket.write(':tmi.twitch.tv 005 '+socket.nick+' PREFIX=(qaohv)~&@$+ CHANTYPES=# NETWORK=Twitch :are supported by this server\r\n');
}
else if(message.command === 'JOIN') {
message.params[0].split(',').forEach(function(channel) {
socket.channels[channel] = {
users: {},
topic: 'Welcome to the channel!',
timer: setInterval(function() { socket.channels[channel].update() }, 20000),
update: function() {
request.get({
url: 'https://tmi.twitch.tv/group/user/'+channel.replace('#','')+'/chatters',
json: true
}, function(err, res, data) {
var userList = socket.channels[channel].users;
if(data.chatters) {
var currentUsers = Object.keys(userList);
var newUsers = [];
var chatterTypes = Object.keys(data.chatters);
for(var i=0; i<chatterTypes.length; i++) {
newUsers = newUsers.concat(data.chatters[chatterTypes[i]]);
}
var joins = [];
var parts = [];
var modes = [];
currentUsers.forEach(function(user) {
if(newUsers.indexOf(user) === -1 && socket.nick !== user) {
delete userList[user];
parts.push(user);
}
});
for(var i=0; i<chatterTypes.length; i++) {
data.chatters[chatterTypes[i]].forEach(function(user) {
if(!userList[user]) {
userList[user] = {
owner: false,
moderator: false,
turbo: false,
subscriber: false,
admin: false,
staff: false
}
joins.push(user);
}
if(channel.replace('#','') === user && !userList[user].owner) {
userList[user].owner = true;
modes.push('+o '+user);
}
if(chatterTypes[i] === 'moderators' && !userList[user].moderator) {
userList[user].moderator = true;
modes.push('+o '+user);
} else if(chatterTypes[i] === 'viewers' && userList[user].moderator && data.chatters['moderators'].length > 0) {
userList[user].moderator = false;
modes.push('-o '+user);
}
if(chatterTypes[i] === 'staff' && !userList[user].staff) {
userList[user].staff = true;
modes.push('+qo '+user);
}
if(chatterTypes[i] === 'admins' && !userList[user].admin) {
userList[user].admin = true;
modes.push('+ao '+user);
}
});
}
if(joins.length < 100) {
while(joins.length) {
var user = joins.splice(0, 1).toString();
socket.write(':'+user+'!'+user+'@'+user+'.tmi.twitch.tv JOIN '+channel+'\r\n');
}
while(parts.length) {
var user = parts.splice(0, 1).toString();
socket.write(':'+user+'!'+user+'@'+user+'.tmi.twitch.tv PART '+channel+'\r\n');
}
} else {
while(newUsers.length) {
var users = newUsers.splice(0, 15).join(' ');
socket.write(':tmi.twitch.tv 353 '+socket.nick+' = '+channel+' :'+users+'\r\n');
}
socket.write(':tmi.twitch.tv 366 '+socket.nick+' '+channel+' :End of /NAMES list\r\n');
}
while(modes.length) {
var mode = modes.splice(0, 1).toString();
socket.write(':Twitch MODE '+channel+' '+mode+'\r\n');
}
}
})
}
}
socket.channels[channel].update();
});
}
else if(message.command === 'PART') {
message.params[0].split(',').forEach(function(channel) {
if(socket.channels[channel]) {
clearInterval(socket.channels[channel].timer);
delete socket.channels[channel];
}
});
}
else if(message.command === 'ISON') {
socket.write(':tmi.twitch.tv 303 '+socket.nick+' :'+message.params.join(' ')+'\r\n');
return;
}
else if(message.command.toUpperCase() === 'SLOW') {
if(!message.params[1]) message.params[1] = '120';
socket.irc.write(':tmi.twitch.tv PRIVMSG '+message.params[0]+' :/slow '+message.params[1].trim()+'\r\n');
return;
}
else if(message.command === 'KICK' || message.command.toUpperCase() === 'TIMEOUT') {
if(!message.params[2]) message.params[2] = '600';
socket.irc.write(':tmi.twitch.tv PRIVMSG '+message.params[0]+' :/timeout '+message.params[1].trim()+' '+message.params[2].trim()+'\r\n');
socket.write(':Twitch NOTICE '+message.params[0]+' :You have timed out '+message.params[1].trim()+' for '+message.params[2]+' seconds.'+'\r\n');
return;
}
else if(message.command.match(/^(?:un)?ban$/i)) {
socket.irc.write(':tmi.twitch.tv PRIVMSG '+message.params[0]+' :/'+message.command.toLowerCase()+' '+message.params[1].trim()+'\r\n');
socket.write(':Twitch NOTICE '+message.params[0]+' :You have '+message.command.toLowerCase()+'ned '+message.params[1].trim()+'\r\n');
return;
}
else if(message.command === 'MODE') {
if(message.params[1] === '+b' || message.params[1] === '-b') {
if(!message.params[2]) return;
if(messageTools.prefixIsHostmask(message.params[2])) {
var hostmask = messageTools.parseHostmaskFromPrefix(message.params[2]);
var user;
if(hostmask.nickname && hostmask.nickname !== '*') {
user = hostmask.nickname;
} else if(hostmask.username && hostmask.username !== '*') {
user = hostmask.username;
} else if(hostmask.hostname && hostmask.hostname !== '*') {
user = hostmask.hostname.split('.')[0];
} else {
user = socket.nick;
}
} else {
var user = message.params[2];
}
var command = (message.params[1] === '+b') ? 'ban' : 'unban';
socket.irc.write(':tmi.twitch.tv PRIVMSG '+message.params[0]+' :/'+command+' '+user+'\r\n');
socket.write(':Twitch NOTICE '+message.params[0]+' :You have '+command+'ned '+user+'.\r\n');
}
return;
}
else if(message.command === 'WHO') {
socket.write(':tmi.twitch.tv 315 '+socket.nick+' '+message.params[0]+' :End of /WHO list.'+'\r\n');
return;
}
else {
var params = '';
var length = message.params.length;
for (var i = 1; i < length; i++) {
params += ' ' + message.params[i];
}
params = params.trim();
socket.irc.write(':tmi.twitch.tv PRIVMSG '+message.params[0]+' :/'+message.command.toLowerCase()+' '+params+'\r\n');
}
socket.irc.write(data+'\r\n');
}
server.listen(6969);
| CLEARCHAT handler | index.js | CLEARCHAT handler | <ide><path>ndex.js
<ide> socket.write(':Twitch MODE '+channel+' -f\r\n');
<ide> socket.write(':Twitch TOPIC '+channel+' '+slowTopic[channel]+subTopic[channel]+'\r\n');
<ide> }
<add> }
<add> else if(jtvData[0] === 'CLEARCHAT') {
<add> socket.write(':Twitch NOTICE '+channel+' :'+jtvData[1]+' has been timed out or banned\r\n');
<ide> }
<ide> else if(jtvData[0].match(/(?:Now|USERCOLOR|EMOTESET)/)) {
<ide> return; |
|
Java | mit | e545e3a36b404859e051c7bdce2c640b7842add3 | 0 | thelinmichael/spotify-web-api-java,thelinmichael/spotify-web-api-java | package com.wrapper.spotify.objects;
import java.util.List;
public class Category extends AbstractModelObject {
private final String href;
private final List<Image> icons;
private final String id;
private final String name;
private Category(final Category.Builder builder) {
super(builder);
this.href = builder.href;
this.icons = builder.icons;
this.id = builder.id;
this.name = builder.name;
}
public String getHref() {
return href;
}
public List<Image> getIcons() {
return icons;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
@Override
public Builder builder() {
return new Builder();
}
public static final class Builder extends AbstractModelObject.Builder<ArtistSimplified.Builder> {
private String href;
private List<Image> icons;
private String id;
private String name;
public Builder setHref(String href) {
this.href = href;
return this;
}
public Builder setIcons(List<Image> icons) {
this.icons = icons;
return this;
}
public Builder setId(String id) {
this.id = id;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
@Override
public Category build() {
return new Category(this);
}
}
}
| src/main/java/com/wrapper/spotify/objects/Category.java | package com.wrapper.spotify.objects;
import java.util.List;
public class Category {
private String href;
private List<Image> icons;
private String id;
private String name;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public List<Image> getIcons() {
return icons;
}
public void setIcons(List<Image> icons) {
this.icons = icons;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| Builder: Category
~ Category object rewrite for builder implementation | src/main/java/com/wrapper/spotify/objects/Category.java | Builder: Category | <ide><path>rc/main/java/com/wrapper/spotify/objects/Category.java
<ide>
<ide> import java.util.List;
<ide>
<del>public class Category {
<add>public class Category extends AbstractModelObject {
<add> private final String href;
<add> private final List<Image> icons;
<add> private final String id;
<add> private final String name;
<ide>
<del> private String href;
<del> private List<Image> icons;
<del> private String id;
<del> private String name;
<add> private Category(final Category.Builder builder) {
<add> super(builder);
<add>
<add> this.href = builder.href;
<add> this.icons = builder.icons;
<add> this.id = builder.id;
<add> this.name = builder.name;
<add> }
<ide>
<ide> public String getHref() {
<ide> return href;
<del> }
<del>
<del> public void setHref(String href) {
<del> this.href = href;
<ide> }
<ide>
<ide> public List<Image> getIcons() {
<ide> return icons;
<ide> }
<ide>
<del> public void setIcons(List<Image> icons) {
<del> this.icons = icons;
<del> }
<del>
<ide> public String getId() {
<ide> return id;
<del> }
<del>
<del> public void setId(String id) {
<del> this.id = id;
<ide> }
<ide>
<ide> public String getName() {
<ide> return name;
<ide> }
<ide>
<del> public void setName(String name) {
<del> this.name = name;
<add> @Override
<add> public Builder builder() {
<add> return new Builder();
<ide> }
<ide>
<add> public static final class Builder extends AbstractModelObject.Builder<ArtistSimplified.Builder> {
<add> private String href;
<add> private List<Image> icons;
<add> private String id;
<add> private String name;
<add>
<add> public Builder setHref(String href) {
<add> this.href = href;
<add> return this;
<add> }
<add>
<add> public Builder setIcons(List<Image> icons) {
<add> this.icons = icons;
<add> return this;
<add> }
<add>
<add> public Builder setId(String id) {
<add> this.id = id;
<add> return this;
<add> }
<add>
<add> public Builder setName(String name) {
<add> this.name = name;
<add> return this;
<add> }
<add>
<add> @Override
<add> public Category build() {
<add> return new Category(this);
<add> }
<add> }
<ide> } |
|
Java | apache-2.0 | 2c3417936f7d983da0d3caf83294ab9ca0751f67 | 0 | ResearchWorx/Cresco-Agent | package core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import org.apache.commons.configuration.ConfigurationException;
import channels.MsgInQueue;
import channels.MsgOutQueue;
import plugins.ConfigPlugins;
import plugins.PluginLoader;
import shared.Clogger;
import shared.MsgEvent;
import shared.MsgEventType;
import shared.PluginInterface;
import shared.RandomString;
//add rand
public class AgentEngine {
public static boolean isActive = false; //agent on/off
public static WatchDog wd;
public static boolean hasChannel = false;
public static String channelPluginSlot;
public static boolean isRegionalController = false;
public static String controllerPluginSlot;
public static boolean isCommInit = false;
public static ConcurrentLinkedQueue<MsgEvent> msgInQueue;
public static Thread MsgInQueueThread;
public static boolean MsgInQueueEnabled = false; //control service on/off
public static boolean MsgInQueueActive = false; //control service on/off
public static ConcurrentLinkedQueue<MsgEvent> msgOutQueue;
public static Thread MsgOutQueueThread;
public static boolean MsgOutQueueEnabled = false; //control service on/off
public static boolean MsgOutQueueActive = false; //control service on/off
public static boolean ControllerEnabled = false; //control service on/off
public static boolean ControllerActive = false; //control service on/off
public static CommandExec commandExec;
public static boolean watchDogActive = false; //agent watchdog on/off
public static String agentVersion = null;
public static Map<String, PluginInterface> pluginMap;
public static Config config;
public static ConfigPlugins pluginsconfig;
public static String region;
public static String agent;
public static Clogger clog;
public static DelayedShutdown ds; //delayed shutdown command
public static void main(String[] args) throws Exception {
try
{
//create command group
commandExec = new CommandExec();
//create logger and base queue
msgInQueue = new ConcurrentLinkedQueue<MsgEvent>();
msgOutQueue = new ConcurrentLinkedQueue<MsgEvent>();
//Cleanup on Shutdown
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
try{
cleanup();
}
catch(Exception ex)
{
System.out.println("Exception Shutting Down:" + ex.toString());
}
}
}, "Shutdown-thread"));
//Make sure initial input is sane.
String configFile = checkConfig(args);
//Make sure config file
config = new Config(configFile);
/*
System.out.println("Building MsgOutQueue");
//start outgoing queue
MsgOutQueue moq = new MsgOutQueue();
MsgOutQueueThread = new Thread(moq);
MsgOutQueueThread.start();
while(!MsgOutQueueEnabled)
{
Thread.sleep(100);
}
*/
System.out.println("Building MsgInQueue");
//start incoming queue
MsgInQueue miq = new MsgInQueue();
MsgInQueueThread = new Thread(miq);
MsgInQueueThread.start();
while(!MsgInQueueEnabled)
{
Thread.sleep(100);
}
/*
//Generate Random Agent String
RandomString rs = new RandomString(4);
if(config.getGenerateName())
{
String AgentName = "agent-" + rs.nextString();
config.setAgentName(AgentName);
}
//Generate Random Region String
if(config.getGenerateRegion())
{
String Region = "region-" + rs.nextString();
config.setRegionName(Region);
}
*/
region = "init"; //set temp setting to allow routing
agent = "init"; //region and agent will come from controller
//Establish a named map of plugin interfaces
pluginMap = new ConcurrentHashMap<String,PluginInterface>();
//build initial plugin list
processPlugins();
//and launch static plugins
//enableStaticPlugins()
//delay and waiting for network init.
int startupdelay = Integer.parseInt(config.getParams("general", "startupdelay"));
Thread.sleep(startupdelay);
LoadControllerPlugin();
isActive = true;
System.out.println("REGION NAME:[" +config.getRegion() +"]");
System.out.println("REGION CONTROLLER:[" + AgentEngine.isRegionalController +"]");
System.out.println("AGENT NAME:[" +config.getAgentName() +"]");
while(isActive)
{
//just sleep until isActive=false
//need to add ability to control other threads here.
//need to add upgrade ability
Thread.sleep(1000);
}
//Die here
System.out.println("SYSTEM EXIT");
System.exit(0);
//set version name
agentVersion = new String(getVersion());
//set region and agent
agent = config.getAgentName();
region = config.getRegion();
clog = new Clogger(msgInQueue,region,agent,null);
//Establish a named map of plugin interfaces
//pluginMap = new ConcurrentHashMap<String,PluginInterface>();
//if channel was not configured during startup try and establish
if(!hasChannel)
{
getChannel(); //currently AMPQ and REST plugins
}
//if controller was not configured during startup try and establish
if(!ControllerActive)
{
getController();
}
//start core watchdog
wd = new WatchDog();
/*
while(isActive)
{
//just sleep until isActive=false
//need to add ability to control other threads here.
//need to add upgrade ability
Thread.sleep(1000);
}
*/
System.exit(0);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Error AgentCore: " + e.getMessage());
}
finally
{
System.out.println("Agent : Main :Finally Statement");
}
}
public static void LoadControllerPlugin() throws InterruptedException
{
boolean isComm = enablePlugin("plugin/0", false);
if(!isComm)
{
System.out.println("failed to load");
System.exit(0);
}
else
{
MsgInQueueActive = true; //allow incoming message
PluginInterface pi = AgentEngine.pluginMap.get("plugin/0");
MsgEvent me = new MsgEvent(MsgEventType.CONFIG,region,agent,"plugin/0","comminit");
me.setParam("src_region", region);
me.setParam("src_agent", agent);
me.setParam("dst_region", region);
me.setParam("dst_agent", agent);
me.setParam("dst_plugin", "plugin/0");
pi.msgIn(me); //send msg to plugin
while(!isCommInit)
{
Thread.sleep(1000);
}
}
}
public static void msgIn(MsgEvent me)
{
final MsgEvent ce = me;
try
{
Thread thread = new Thread(){
public void run(){ //command request go in new threads
MsgEvent re = null;
try
{
if(ce == null)
{
System.out.println("Agent : msgIn : Incoming message NULL!!!!");
}
re = commandExec.cmdExec(ce); //execute command
if(re != null)
{
re.setReturn(); //reverse to-from for return
msgInQueue.offer(re);
}
}
catch(Exception ex)
{
clog.error("Agent : AgentEngine : msgIn Thread: " + ex.toString());
clog.error("Agent : AgentEngine : msgIn ce EventMsg =" + ce.getParamsString());
if(re != null)
{
clog.error("Agent : AgentEngine : msgIn re EventMsg =" + re.getParamsString());
}
}
}
};
thread.start(); //start the exec thread
}
catch(Exception ex)
{
clog.error("Agent : AgentEngine : msgIn : " + ex.toString());
}
}
public static void getController() throws InterruptedException, ConfigurationException, IOException
{
if(MsgInQueueActive && MsgOutQueueActive)
{
int tryController = 1;
int controllerDiscoveryTimeout = config.getControllerDiscoveryTimeout();
//add random delay on startup
Random r = new Random();
int Low = 0;
int High = 10000;
int R = r.nextInt(High-Low) + Low;
//
controllerDiscoveryTimeout = (controllerDiscoveryTimeout+R)/1000;//add random delay to startup so only one controller starts
int controllerLaunchTimeout = Math.round(controllerDiscoveryTimeout/2);
//give the controller 20 sec to respond. First 10 for possibe existing,
//last 10 for one we try and start
System.out.println("Waiting for Controller Response Initialization");
while((!ControllerActive) && (tryController < controllerDiscoveryTimeout))
{
System.out.print(".");
if(AgentEngine.channelPluginSlot != null) //controller plugin was found
{
MsgEvent de = clog.getLog("enabled");
de.setMsgType(MsgEventType.CONFIG);
de.setMsgAgent(AgentEngine.agent); //route to this agent
de.setMsgPlugin(AgentEngine.channelPluginSlot); //route to controller plugin
de.setParam("attempt", String.valueOf(tryController));
AgentEngine.commandExec.cmdExec(de);
}
Thread.sleep(1000);
tryController++; //give X trys for controller to respond
//Notify controler of agent enable wait for controller contact
if((tryController > controllerLaunchTimeout) && !isRegionalController)
{
String controllerPlugin = findPlugin("ControllerPlugin",0);
if(controllerPlugin != null)
{
System.out.println("Try and Start our own controller");
//start controller but don't save the config.
isRegionalController = enablePlugin(controllerPlugin, false);
if(!isRegionalController)
{
System.out.println("Controller Plugin NOT Loaded");
}
else
{
System.out.println("Controller Plugin Loaded");
controllerPluginSlot = controllerPlugin;
isActive = true;
//else if(ce.getParam("cmd").equals("enablelogconsumer"))
//enable incoming logs
MsgEvent me = new MsgEvent(MsgEventType.EXEC,region,agent,channelPluginSlot,"Enable Incoming Log");
me.setParam("cmd", "enablelogconsumer");
me.setSrc(region, agent, null);
me.setDst(region, agent, channelPluginSlot);
AgentEngine.msgInQueue.offer(me); //enable the incoming queue
//if controller is active enable REST interface
/*
String RESTPlugin = findPlugin("RESTPlugin",0);
if(controllerPlugin != null)
{
System.out.println("Start RESTChannel for Controller on port 32001");
boolean isREST = enablePlugin(RESTPlugin, false);
if(!isREST)
{
System.out.println("RESTChannel Plugin NOT Loaded");
}
}
*/
}
}
}
}
if(ControllerActive)
{
System.out.println("Region:" + config.getRegion() + " Controller found:");
}
else
{
System.out.println("Region:" + config.getRegion() + " *NOT* Controller found:");
}
//wait until shutdown occures
isActive = true;
//Notify log that agent has started
String msg = "Agent Core (" + agentVersion + ") Started";
clog.log(msg);
}
else
{
System.out.println("Agent is a Zombie!\nNo Active Log or Control Channels!\nAgent will now shutdown.");
isActive = false;
}
}
public static void getChannel()
{
//Try and load some plugins to establish comm
//while here not explicit names
//commpluginlist="cresco-agent-ampqchannel-plugin"
String commpluginlist = AgentEngine.config.getParams("communication", "commpluginlist");
String[] commList = commpluginlist.split(",");
int i = 0;
while((i<commList.length) && !hasChannel)
{
try
{
String commPlugin = findPlugin(commList[i],0);
if(commPlugin != null)
{
//start controller but don't save the config.
boolean isComm = enablePlugin(commPlugin, false);
if(!isComm)
{
System.out.println(commList[i] + " is not enabled");
}
else
{
//turn on queues and set channel
MsgInQueueActive = true;
MsgOutQueueActive = true;
hasChannel = true;
channelPluginSlot = commPlugin;
}
}
else
{
System.out.println("NO configuration found for communication plugin " + commList[i]);
}
}
catch(Exception ex)
{
System.out.println("Error creating communication channel using plugin " + commList[i]);
}
i++;
}
if(!hasChannel)
{
System.out.println("Unable to create communication channel.. exiting");
System.exit(0);
}
}
public static void getChannel2()
{
//Try and load some plugins to establish comm
//while here not explicit names
try
{
String ampqPlugin = findPlugin("cresco-agent-ampqchannel-plugin",0);
if(ampqPlugin != null)
{
//start controller but don't save the config.
boolean isAMPQ = enablePlugin(ampqPlugin, false);
if(!isAMPQ)
{
System.out.println("AMPQ is not enabled");
}
else
{
//turn on queues and set channel
MsgInQueueActive = true;
MsgOutQueueActive = true;
hasChannel = true;
channelPluginSlot = ampqPlugin;
}
}
else
{
System.out.println("NO AMPQPlugin found.. falling back to REST");
}
if(!hasChannel)
{
System.out.println("Starting REST Plugin");
String restPlugin = findPlugin("RESTPlugin",0);
if(restPlugin != null)
{
//start controller but don't save the config.
boolean isREST = enablePlugin(restPlugin, false);
//System.out.println("Enabled AMPQ Module [" + ampqSlot + "]");
if(!isREST)
{
System.out.println("REST is not enabled.. No communication channel.. exiting");
System.exit(0);
}
else
{
MsgInQueueActive = true;
MsgOutQueueActive = true;
hasChannel = true;
channelPluginSlot = ampqPlugin;
}
}
else
{
System.out.println("NO RESTPlugin found.. No communication channel.. exiting");
System.exit(0);
}
}
}
catch(Exception ex)
{
System.out.println("Error creating communication channel.. exiting");
System.exit(0);
}
}
public static String checkConfig(String[] args)
{
String errorMgs = "Cresco-Agent\n" +
"Usage: java -jar Cresco-Agent.jar" +
" -f <configuration_file>\n";
if (args.length != 2)
{
System.err.println(errorMgs);
System.err.println("ERROR: Invalid number of arguements.");
System.exit(1);
}
else if(!args[0].equals("-f"))
{
System.err.println(errorMgs);
System.err.println("ERROR: Must specify configuration file.");
System.exit(1);
}
else
{
File f = new File(args[1]);
if(!f.exists())
{
System.err.println("The specified configuration file: " + args[1] + " is invalid");
System.exit(1);
}
}
return args[1];
}
public static void processPlugins() throws ClassNotFoundException, IOException
{
try
{
System.out.println("Start process plugins");
String plugin_config_file = config.getPluginConfigFile();
System.out.println("Start process plugins " + plugin_config_file);
File f = new File(plugin_config_file);
if(!f.exists())
{
String msg = "The specified configuration file: " + plugin_config_file + " is invalid";
clog.error(msg);
System.exit(1);
}
System.out.println("PluginFile=" + plugin_config_file);
//pull in plugin configuration
pluginsconfig = new ConfigPlugins(plugin_config_file);
}
catch(Exception ex)
{
String msg = "Failed to Process Plugins: Agent=" + AgentEngine.agent + " ERROR:" + ex.toString();
clog.error(msg);
}
}
public static void enableStaticPlugins()
{
try
{
if(pluginsconfig !=null)
{
@SuppressWarnings("unchecked")
List<String> enabledPlugins = pluginsconfig.getPluginList(1);//return enabled values in the config
for(String pluginName : enabledPlugins) //process list of plugins that should be enabled
{
boolean isLoaded = enablePlugin(pluginName, false);
if(!isLoaded)
{
System.out.println("Failed Loading Required Plugin: " + pluginName + " " + pluginsconfig.getPluginJar(pluginName) + " exiting..");
System.exit(0); //exit if required plugin fails
}
}
}
else
{
String msg = "No static plugins to load!";
clog.error(msg);
}
}
catch(Exception ex)
{
String msg = "Failed to Process Plugins: Agent=" + AgentEngine.agent + " ERROR:" + ex.toString();
clog.error(msg);
}
}
public static boolean disablePlugin(String plugin, boolean save) //loop through known plugins on agent
{
try
{
if(pluginMap.containsKey(plugin))
{
//PluginNode pn = pluginMap.get(plugin);
PluginInterface pi = pluginMap.get(plugin);
pi.shutdown();
String msg = "Plugin Configuration: [" + plugin + "] Removed: (" + pi.getVersion() + ")";
pi = null;
System.out.println(msg);
pluginMap.remove(plugin);
if(save)
{
pluginsconfig.setPluginStatus(plugin, 0);//save in config
}
return true;
}
else
{
//already disabled
System.out.println("Plugin " + plugin + " is already disabled");
return false;
}
}
catch(Exception ex)
{
String msg = "Plugin Failed Disable: Agent=" + AgentEngine.agent + "pluginname=" + pluginsconfig.getPluginName(plugin);
clog.error(msg);
return false;
}
}
public static boolean enablePlugin(String plugin, boolean save) //loop through known plugins on agent
{
try
{
if(!pluginMap.containsKey(plugin))
{
PluginLoader pl = new PluginLoader(pluginsconfig.getPluginJar(plugin));
PluginInterface pi = pl.getPluginInterface();
//if(pi.initialize(msgOutQueue,msgInQueue,pluginsconfig.getPluginConfig(plugin),AgentEngine.config.getRegion(),AgentEngine.config.getAgentName(),plugin))
if(pi.initialize(msgOutQueue,msgInQueue,pluginsconfig.getPluginConfig(plugin),AgentEngine.region,AgentEngine.agent,plugin))
{
boolean versionMatch = pluginsconfig.getPluginName(plugin).equals(pi.getName());
if(versionMatch)
{
try
{
String msg = "Plugin Configuration: [" + plugin + "] Initialized: (" + pi.getName() + " Version: " + pi.getVersion() + ")";
//clog.log(msg);
System.out.println(msg);
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Plugin Configuration: pq.getVersion() Error: " + ex.toString());
}
pluginMap.put(plugin, pi);
if(save)
{
pluginsconfig.setPluginStatus(plugin, 1);
}
return true;
}
else
{
String msg = "Plugin Configuration: Agent=" + AgentEngine.agent + " pluginname=" + pluginsconfig.getPluginName(plugin) + " does not match reported plugin Jar name: " + pi.getName();
pluginMap.put(plugin, pi);
//clog.error(msg);
pl = null;
pi = null;
System.out.println(msg);
return false;
}
}
else
{
String msg = "Plugin Failed Initialization: Agent=" + AgentEngine.agent + " pluginname=" + pluginsconfig.getPluginName(plugin) + " does not match Plugin Jar: " + pi.getVersion() + ")";
clog.error(msg);
System.out.println(msg);
return false;
}
}
else
{
System.out.println("Plugin " + plugin + " is already active");
return false;
}
}
catch(Exception ex)
{
//String msg = "Plugin Failed Initialization: Agent=" + AgentEngine.agent + "pluginname=" + pluginsconfig.getPluginName(plugin) + " Error: " + ex.toString();
String msg = "Plugin Failed Initialization: pluginname=" + pluginsconfig.getPluginName(plugin) + " Error: " + ex.getMessage();
//clog.error(msg);
ex.printStackTrace();
System.out.println(msg);
return false;
}
}
public static String getVersion() //This should pull the version information from jar Meta data
{
String version;
try{
String jarFile = AgentEngine.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println("JARFILE:" + jarFile);
//File file = new File(jarFile.substring(5, (jarFile.length() )));
File file = new File(jarFile);
FileInputStream fis = new FileInputStream(file);
@SuppressWarnings("resource")
JarInputStream jarStream = new JarInputStream(fis);
Manifest mf = jarStream.getManifest();
Attributes mainAttribs = mf.getMainAttributes();
version = mainAttribs.getValue("Implementation-Version");
}
catch(Exception ex)
{
String msg = "Unable to determine Plugin Version " + ex.toString();
System.err.println(msg);
version = "Unable to determine Version";
}
return config.getAgentName() + "." + version;
}
//This needs to be redone to account for active but not configured
public static String findPlugin(String searchPluginName, int isActive) //loop through known plugins on agent
{
System.out.println("Searching for plugin: " + searchPluginName);
StringBuilder sb = new StringBuilder();
List<String> pluginList = AgentEngine.pluginsconfig.getPluginList(isActive);
if(pluginList.size() > 0)
{
for(String pluginName : pluginList)
{
if(AgentEngine.pluginsconfig.getPluginName(pluginName).equals(searchPluginName))
{
if((isActive == 0) && !AgentEngine.pluginMap.containsKey(pluginName))
{
System.out.println("PluginFound: " + searchPluginName + "=" + pluginName);
return pluginName;
}
}
}
return null;
}
else
{
return null;
}
}
//needs to be redone to account for active and configured.
public static String listPlugins() //loop through known plugins on agent
{
StringBuilder sb = new StringBuilder();
List<String> pluginListEnabled = new ArrayList<String>(AgentEngine.pluginsconfig.getPluginList(1));
List<String> pluginListDisabled = new ArrayList<String>(AgentEngine.pluginsconfig.getPluginList(0));
List<String> pluginListActive = getActivePlugins();
if((pluginListEnabled.size() > 0) || (pluginListDisabled.size() > 0))
{
if((pluginListEnabled.size() > 0) || (pluginListActive.size() > 0))
{
sb.append("Enabled Plugins:\n");
}
for(String pluginName : pluginListEnabled)
{
if((AgentEngine.pluginMap.containsKey(pluginName)) && !pluginListActive.contains(pluginName))
{
PluginInterface pi = pluginMap.get(pluginName);
sb.append("Plugin: [" + pluginName + "] Name: " + AgentEngine.pluginsconfig.getPluginName(pluginName) + " Initialized: " + pi.getVersion() + "\n");
}
}
for(String pluginName : pluginListActive)
{
PluginInterface pi = pluginMap.get(pluginName);
sb.append("Plugin: [" + pluginName + "] Name: " + AgentEngine.pluginsconfig.getPluginName(pluginName) + " Initialized: " + pi.getVersion() + "\n");
}
if(pluginListDisabled.size() > 0)
{
sb.append("Disabled Plugins:\n");
}
for(String pluginName : pluginListDisabled)
{
if(!pluginListActive.contains(pluginName))
{
sb.append("Plugin: [" + pluginName + "] Name: " + AgentEngine.pluginsconfig.getPluginName(pluginName) + "\n");
}
}
}
else
{
sb.append("No Plugins Found!\n");
}
return sb.toString().substring(0,sb.toString().length()-1);
}
static List<String> getActivePlugins()
{
List<String> pluginList = new ArrayList<String>();
if(pluginMap != null)
{
Iterator it = pluginMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
String plugin = pairs.getKey().toString();
//disablePlugin(plugin,false);
pluginList.add(plugin);
//it.remove(); // avoids a ConcurrentModificationException
}
}
return pluginList;
}
static void cleanup() throws ConfigurationException, IOException, InterruptedException
{
System.out.println("Shutdown:Cleaning Active Agent Resources");
wd.timer.cancel();
List<String> pluginList = getActivePlugins();
/*
for(String plugin : pluginList)
{
if(((isController) && (plugin.equals(channelPluginSlot))))
{
}
else
{
//disablePlugin(plugin,false);
}
}
*/
/*
if(pluginMap != null)
{
Iterator it = pluginMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
String plugin = pairs.getKey().toString();
disablePlugin(plugin,false);
it.remove(); // avoids a ConcurrentModificationException
}
}
*/
if(!isRegionalController)
{
for(String plugin : pluginList)
{
if(!plugin.equals(channelPluginSlot))
{
disablePlugin(plugin,false);
}
}
if(msgInQueue != null)
{
MsgEvent de = clog.getLog("disabled");
de.setMsgType(MsgEventType.CONFIG);
de.setMsgAgent(AgentEngine.agent); //route to this agent
de.setMsgPlugin(AgentEngine.channelPluginSlot); //route to controller plugin
de.setParam("src_region",region);
de.setParam("src_agent",agent);
de.setParam("dst_region",region);
AgentEngine.commandExec.cmdExec(de);
Thread.sleep(5000);
disablePlugin(channelPluginSlot,false);
/*
int time = 0;
int timeout = 30; //give 30sec to timeout from RPC request
if(MsgInQueueThread != null)
{
//disablePlugin(controllerPluginSlot,false);
//disablePlugin(controllerPluginSlot,false);
disablePlugin(channelPluginSlot,false);
while((MsgInQueueThread.isAlive()) && (time < timeout))
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
time++;
}
}
*/
}
}
else
{
//cleanup controller here
for(String plugin : pluginList)
{
disablePlugin(plugin,false);
}
}
}
}
| src/main/java/core/AgentEngine.java | package core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import org.apache.commons.configuration.ConfigurationException;
import channels.MsgInQueue;
import channels.MsgOutQueue;
import plugins.ConfigPlugins;
import plugins.PluginLoader;
import shared.Clogger;
import shared.MsgEvent;
import shared.MsgEventType;
import shared.PluginInterface;
import shared.RandomString;
//add rand
public class AgentEngine {
public static boolean isActive = false; //agent on/off
public static WatchDog wd;
public static boolean hasChannel = false;
public static String channelPluginSlot;
public static boolean isRegionalController = false;
public static String controllerPluginSlot;
public static boolean isCommInit = false;
public static ConcurrentLinkedQueue<MsgEvent> msgInQueue;
public static Thread MsgInQueueThread;
public static boolean MsgInQueueEnabled = false; //control service on/off
public static boolean MsgInQueueActive = false; //control service on/off
public static ConcurrentLinkedQueue<MsgEvent> msgOutQueue;
public static Thread MsgOutQueueThread;
public static boolean MsgOutQueueEnabled = false; //control service on/off
public static boolean MsgOutQueueActive = false; //control service on/off
public static boolean ControllerEnabled = false; //control service on/off
public static boolean ControllerActive = false; //control service on/off
public static CommandExec commandExec;
public static boolean watchDogActive = false; //agent watchdog on/off
public static String agentVersion = null;
public static Map<String, PluginInterface> pluginMap;
public static Config config;
public static ConfigPlugins pluginsconfig;
public static String region;
public static String agent;
public static Clogger clog;
public static DelayedShutdown ds; //delayed shutdown command
public static void main(String[] args) throws Exception {
try
{
//create command group
commandExec = new CommandExec();
//create logger and base queue
msgInQueue = new ConcurrentLinkedQueue<MsgEvent>();
msgOutQueue = new ConcurrentLinkedQueue<MsgEvent>();
//Cleanup on Shutdown
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
try{
cleanup();
}
catch(Exception ex)
{
System.out.println("Exception Shutting Down:" + ex.toString());
}
}
}, "Shutdown-thread"));
//Make sure initial input is sane.
String configFile = checkConfig(args);
//Make sure config file
config = new Config(configFile);
/*
System.out.println("Building MsgOutQueue");
//start outgoing queue
MsgOutQueue moq = new MsgOutQueue();
MsgOutQueueThread = new Thread(moq);
MsgOutQueueThread.start();
while(!MsgOutQueueEnabled)
{
Thread.sleep(100);
}
*/
System.out.println("Building MsgInQueue");
//start incoming queue
MsgInQueue miq = new MsgInQueue();
MsgInQueueThread = new Thread(miq);
MsgInQueueThread.start();
while(!MsgInQueueEnabled)
{
Thread.sleep(100);
}
/*
//Generate Random Agent String
RandomString rs = new RandomString(4);
if(config.getGenerateName())
{
String AgentName = "agent-" + rs.nextString();
config.setAgentName(AgentName);
}
//Generate Random Region String
if(config.getGenerateRegion())
{
String Region = "region-" + rs.nextString();
config.setRegionName(Region);
}
*/
region = "init"; //set temp setting to allow routing
agent = "init"; //region and agent will come from controller
//Establish a named map of plugin interfaces
pluginMap = new ConcurrentHashMap<String,PluginInterface>();
//build initial plugin list
processPlugins();
//and launch static plugins
//enableStaticPlugins()
LoadControllerPlugin();
isActive = true;
System.out.println("REGION NAME:[" +config.getRegion() +"]");
System.out.println("REGION CONTROLLER:[" + AgentEngine.isRegionalController +"]");
System.out.println("AGENT NAME:[" +config.getAgentName() +"]");
while(isActive)
{
//just sleep until isActive=false
//need to add ability to control other threads here.
//need to add upgrade ability
Thread.sleep(1000);
}
//Die here
System.out.println("SYSTEM EXIT");
System.exit(0);
//set version name
agentVersion = new String(getVersion());
//set region and agent
agent = config.getAgentName();
region = config.getRegion();
clog = new Clogger(msgInQueue,region,agent,null);
//Establish a named map of plugin interfaces
//pluginMap = new ConcurrentHashMap<String,PluginInterface>();
//if channel was not configured during startup try and establish
if(!hasChannel)
{
getChannel(); //currently AMPQ and REST plugins
}
//if controller was not configured during startup try and establish
if(!ControllerActive)
{
getController();
}
//start core watchdog
wd = new WatchDog();
/*
while(isActive)
{
//just sleep until isActive=false
//need to add ability to control other threads here.
//need to add upgrade ability
Thread.sleep(1000);
}
*/
System.exit(0);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Error AgentCore: " + e.getMessage());
}
finally
{
System.out.println("Agent : Main :Finally Statement");
}
}
public static void LoadControllerPlugin() throws InterruptedException
{
boolean isComm = enablePlugin("plugin/0", false);
if(!isComm)
{
System.out.println("failed to load");
System.exit(0);
}
else
{
MsgInQueueActive = true; //allow incoming message
PluginInterface pi = AgentEngine.pluginMap.get("plugin/0");
MsgEvent me = new MsgEvent(MsgEventType.CONFIG,region,agent,"plugin/0","comminit");
me.setParam("src_region", region);
me.setParam("src_agent", agent);
me.setParam("dst_region", region);
me.setParam("dst_agent", agent);
me.setParam("dst_plugin", "plugin/0");
pi.msgIn(me); //send msg to plugin
while(!isCommInit)
{
Thread.sleep(1000);
}
}
}
public static void msgIn(MsgEvent me)
{
final MsgEvent ce = me;
try
{
Thread thread = new Thread(){
public void run(){ //command request go in new threads
MsgEvent re = null;
try
{
if(ce == null)
{
System.out.println("Agent : msgIn : Incoming message NULL!!!!");
}
re = commandExec.cmdExec(ce); //execute command
if(re != null)
{
re.setReturn(); //reverse to-from for return
msgInQueue.offer(re);
}
}
catch(Exception ex)
{
clog.error("Agent : AgentEngine : msgIn Thread: " + ex.toString());
clog.error("Agent : AgentEngine : msgIn ce EventMsg =" + ce.getParamsString());
if(re != null)
{
clog.error("Agent : AgentEngine : msgIn re EventMsg =" + re.getParamsString());
}
}
}
};
thread.start(); //start the exec thread
}
catch(Exception ex)
{
clog.error("Agent : AgentEngine : msgIn : " + ex.toString());
}
}
public static void getController() throws InterruptedException, ConfigurationException, IOException
{
if(MsgInQueueActive && MsgOutQueueActive)
{
int tryController = 1;
int controllerDiscoveryTimeout = config.getControllerDiscoveryTimeout();
//add random delay on startup
Random r = new Random();
int Low = 0;
int High = 10000;
int R = r.nextInt(High-Low) + Low;
//
controllerDiscoveryTimeout = (controllerDiscoveryTimeout+R)/1000;//add random delay to startup so only one controller starts
int controllerLaunchTimeout = Math.round(controllerDiscoveryTimeout/2);
//give the controller 20 sec to respond. First 10 for possibe existing,
//last 10 for one we try and start
System.out.println("Waiting for Controller Response Initialization");
while((!ControllerActive) && (tryController < controllerDiscoveryTimeout))
{
System.out.print(".");
if(AgentEngine.channelPluginSlot != null) //controller plugin was found
{
MsgEvent de = clog.getLog("enabled");
de.setMsgType(MsgEventType.CONFIG);
de.setMsgAgent(AgentEngine.agent); //route to this agent
de.setMsgPlugin(AgentEngine.channelPluginSlot); //route to controller plugin
de.setParam("attempt", String.valueOf(tryController));
AgentEngine.commandExec.cmdExec(de);
}
Thread.sleep(1000);
tryController++; //give X trys for controller to respond
//Notify controler of agent enable wait for controller contact
if((tryController > controllerLaunchTimeout) && !isRegionalController)
{
String controllerPlugin = findPlugin("ControllerPlugin",0);
if(controllerPlugin != null)
{
System.out.println("Try and Start our own controller");
//start controller but don't save the config.
isRegionalController = enablePlugin(controllerPlugin, false);
if(!isRegionalController)
{
System.out.println("Controller Plugin NOT Loaded");
}
else
{
System.out.println("Controller Plugin Loaded");
controllerPluginSlot = controllerPlugin;
isActive = true;
//else if(ce.getParam("cmd").equals("enablelogconsumer"))
//enable incoming logs
MsgEvent me = new MsgEvent(MsgEventType.EXEC,region,agent,channelPluginSlot,"Enable Incoming Log");
me.setParam("cmd", "enablelogconsumer");
me.setSrc(region, agent, null);
me.setDst(region, agent, channelPluginSlot);
AgentEngine.msgInQueue.offer(me); //enable the incoming queue
//if controller is active enable REST interface
/*
String RESTPlugin = findPlugin("RESTPlugin",0);
if(controllerPlugin != null)
{
System.out.println("Start RESTChannel for Controller on port 32001");
boolean isREST = enablePlugin(RESTPlugin, false);
if(!isREST)
{
System.out.println("RESTChannel Plugin NOT Loaded");
}
}
*/
}
}
}
}
if(ControllerActive)
{
System.out.println("Region:" + config.getRegion() + " Controller found:");
}
else
{
System.out.println("Region:" + config.getRegion() + " *NOT* Controller found:");
}
//wait until shutdown occures
isActive = true;
//Notify log that agent has started
String msg = "Agent Core (" + agentVersion + ") Started";
clog.log(msg);
}
else
{
System.out.println("Agent is a Zombie!\nNo Active Log or Control Channels!\nAgent will now shutdown.");
isActive = false;
}
}
public static void getChannel()
{
//Try and load some plugins to establish comm
//while here not explicit names
//commpluginlist="cresco-agent-ampqchannel-plugin"
String commpluginlist = AgentEngine.config.getParams("communication", "commpluginlist");
String[] commList = commpluginlist.split(",");
int i = 0;
while((i<commList.length) && !hasChannel)
{
try
{
String commPlugin = findPlugin(commList[i],0);
if(commPlugin != null)
{
//start controller but don't save the config.
boolean isComm = enablePlugin(commPlugin, false);
if(!isComm)
{
System.out.println(commList[i] + " is not enabled");
}
else
{
//turn on queues and set channel
MsgInQueueActive = true;
MsgOutQueueActive = true;
hasChannel = true;
channelPluginSlot = commPlugin;
}
}
else
{
System.out.println("NO configuration found for communication plugin " + commList[i]);
}
}
catch(Exception ex)
{
System.out.println("Error creating communication channel using plugin " + commList[i]);
}
i++;
}
if(!hasChannel)
{
System.out.println("Unable to create communication channel.. exiting");
System.exit(0);
}
}
public static void getChannel2()
{
//Try and load some plugins to establish comm
//while here not explicit names
try
{
String ampqPlugin = findPlugin("cresco-agent-ampqchannel-plugin",0);
if(ampqPlugin != null)
{
//start controller but don't save the config.
boolean isAMPQ = enablePlugin(ampqPlugin, false);
if(!isAMPQ)
{
System.out.println("AMPQ is not enabled");
}
else
{
//turn on queues and set channel
MsgInQueueActive = true;
MsgOutQueueActive = true;
hasChannel = true;
channelPluginSlot = ampqPlugin;
}
}
else
{
System.out.println("NO AMPQPlugin found.. falling back to REST");
}
if(!hasChannel)
{
System.out.println("Starting REST Plugin");
String restPlugin = findPlugin("RESTPlugin",0);
if(restPlugin != null)
{
//start controller but don't save the config.
boolean isREST = enablePlugin(restPlugin, false);
//System.out.println("Enabled AMPQ Module [" + ampqSlot + "]");
if(!isREST)
{
System.out.println("REST is not enabled.. No communication channel.. exiting");
System.exit(0);
}
else
{
MsgInQueueActive = true;
MsgOutQueueActive = true;
hasChannel = true;
channelPluginSlot = ampqPlugin;
}
}
else
{
System.out.println("NO RESTPlugin found.. No communication channel.. exiting");
System.exit(0);
}
}
}
catch(Exception ex)
{
System.out.println("Error creating communication channel.. exiting");
System.exit(0);
}
}
public static String checkConfig(String[] args)
{
String errorMgs = "Cresco-Agent\n" +
"Usage: java -jar Cresco-Agent.jar" +
" -f <configuration_file>\n";
if (args.length != 2)
{
System.err.println(errorMgs);
System.err.println("ERROR: Invalid number of arguements.");
System.exit(1);
}
else if(!args[0].equals("-f"))
{
System.err.println(errorMgs);
System.err.println("ERROR: Must specify configuration file.");
System.exit(1);
}
else
{
File f = new File(args[1]);
if(!f.exists())
{
System.err.println("The specified configuration file: " + args[1] + " is invalid");
System.exit(1);
}
}
return args[1];
}
public static void processPlugins() throws ClassNotFoundException, IOException
{
try
{
System.out.println("Start process plugins");
String plugin_config_file = config.getPluginConfigFile();
System.out.println("Start process plugins " + plugin_config_file);
File f = new File(plugin_config_file);
if(!f.exists())
{
String msg = "The specified configuration file: " + plugin_config_file + " is invalid";
clog.error(msg);
System.exit(1);
}
System.out.println("PluginFile=" + plugin_config_file);
//pull in plugin configuration
pluginsconfig = new ConfigPlugins(plugin_config_file);
}
catch(Exception ex)
{
String msg = "Failed to Process Plugins: Agent=" + AgentEngine.agent + " ERROR:" + ex.toString();
clog.error(msg);
}
}
public static void enableStaticPlugins()
{
try
{
if(pluginsconfig !=null)
{
@SuppressWarnings("unchecked")
List<String> enabledPlugins = pluginsconfig.getPluginList(1);//return enabled values in the config
for(String pluginName : enabledPlugins) //process list of plugins that should be enabled
{
boolean isLoaded = enablePlugin(pluginName, false);
if(!isLoaded)
{
System.out.println("Failed Loading Required Plugin: " + pluginName + " " + pluginsconfig.getPluginJar(pluginName) + " exiting..");
System.exit(0); //exit if required plugin fails
}
}
}
else
{
String msg = "No static plugins to load!";
clog.error(msg);
}
}
catch(Exception ex)
{
String msg = "Failed to Process Plugins: Agent=" + AgentEngine.agent + " ERROR:" + ex.toString();
clog.error(msg);
}
}
public static boolean disablePlugin(String plugin, boolean save) //loop through known plugins on agent
{
try
{
if(pluginMap.containsKey(plugin))
{
//PluginNode pn = pluginMap.get(plugin);
PluginInterface pi = pluginMap.get(plugin);
pi.shutdown();
String msg = "Plugin Configuration: [" + plugin + "] Removed: (" + pi.getVersion() + ")";
pi = null;
System.out.println(msg);
pluginMap.remove(plugin);
if(save)
{
pluginsconfig.setPluginStatus(plugin, 0);//save in config
}
return true;
}
else
{
//already disabled
System.out.println("Plugin " + plugin + " is already disabled");
return false;
}
}
catch(Exception ex)
{
String msg = "Plugin Failed Disable: Agent=" + AgentEngine.agent + "pluginname=" + pluginsconfig.getPluginName(plugin);
clog.error(msg);
return false;
}
}
public static boolean enablePlugin(String plugin, boolean save) //loop through known plugins on agent
{
try
{
if(!pluginMap.containsKey(plugin))
{
PluginLoader pl = new PluginLoader(pluginsconfig.getPluginJar(plugin));
PluginInterface pi = pl.getPluginInterface();
//if(pi.initialize(msgOutQueue,msgInQueue,pluginsconfig.getPluginConfig(plugin),AgentEngine.config.getRegion(),AgentEngine.config.getAgentName(),plugin))
if(pi.initialize(msgOutQueue,msgInQueue,pluginsconfig.getPluginConfig(plugin),AgentEngine.region,AgentEngine.agent,plugin))
{
boolean versionMatch = pluginsconfig.getPluginName(plugin).equals(pi.getName());
if(versionMatch)
{
try
{
String msg = "Plugin Configuration: [" + plugin + "] Initialized: (" + pi.getName() + " Version: " + pi.getVersion() + ")";
//clog.log(msg);
System.out.println(msg);
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Plugin Configuration: pq.getVersion() Error: " + ex.toString());
}
pluginMap.put(plugin, pi);
if(save)
{
pluginsconfig.setPluginStatus(plugin, 1);
}
return true;
}
else
{
String msg = "Plugin Configuration: Agent=" + AgentEngine.agent + " pluginname=" + pluginsconfig.getPluginName(plugin) + " does not match reported plugin Jar name: " + pi.getName();
pluginMap.put(plugin, pi);
//clog.error(msg);
pl = null;
pi = null;
System.out.println(msg);
return false;
}
}
else
{
String msg = "Plugin Failed Initialization: Agent=" + AgentEngine.agent + " pluginname=" + pluginsconfig.getPluginName(plugin) + " does not match Plugin Jar: " + pi.getVersion() + ")";
clog.error(msg);
System.out.println(msg);
return false;
}
}
else
{
System.out.println("Plugin " + plugin + " is already active");
return false;
}
}
catch(Exception ex)
{
//String msg = "Plugin Failed Initialization: Agent=" + AgentEngine.agent + "pluginname=" + pluginsconfig.getPluginName(plugin) + " Error: " + ex.toString();
String msg = "Plugin Failed Initialization: pluginname=" + pluginsconfig.getPluginName(plugin) + " Error: " + ex.getMessage();
//clog.error(msg);
ex.printStackTrace();
System.out.println(msg);
return false;
}
}
public static String getVersion() //This should pull the version information from jar Meta data
{
String version;
try{
String jarFile = AgentEngine.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println("JARFILE:" + jarFile);
//File file = new File(jarFile.substring(5, (jarFile.length() )));
File file = new File(jarFile);
FileInputStream fis = new FileInputStream(file);
@SuppressWarnings("resource")
JarInputStream jarStream = new JarInputStream(fis);
Manifest mf = jarStream.getManifest();
Attributes mainAttribs = mf.getMainAttributes();
version = mainAttribs.getValue("Implementation-Version");
}
catch(Exception ex)
{
String msg = "Unable to determine Plugin Version " + ex.toString();
System.err.println(msg);
version = "Unable to determine Version";
}
return config.getAgentName() + "." + version;
}
//This needs to be redone to account for active but not configured
public static String findPlugin(String searchPluginName, int isActive) //loop through known plugins on agent
{
System.out.println("Searching for plugin: " + searchPluginName);
StringBuilder sb = new StringBuilder();
List<String> pluginList = AgentEngine.pluginsconfig.getPluginList(isActive);
if(pluginList.size() > 0)
{
for(String pluginName : pluginList)
{
if(AgentEngine.pluginsconfig.getPluginName(pluginName).equals(searchPluginName))
{
if((isActive == 0) && !AgentEngine.pluginMap.containsKey(pluginName))
{
System.out.println("PluginFound: " + searchPluginName + "=" + pluginName);
return pluginName;
}
}
}
return null;
}
else
{
return null;
}
}
//needs to be redone to account for active and configured.
public static String listPlugins() //loop through known plugins on agent
{
StringBuilder sb = new StringBuilder();
List<String> pluginListEnabled = new ArrayList<String>(AgentEngine.pluginsconfig.getPluginList(1));
List<String> pluginListDisabled = new ArrayList<String>(AgentEngine.pluginsconfig.getPluginList(0));
List<String> pluginListActive = getActivePlugins();
if((pluginListEnabled.size() > 0) || (pluginListDisabled.size() > 0))
{
if((pluginListEnabled.size() > 0) || (pluginListActive.size() > 0))
{
sb.append("Enabled Plugins:\n");
}
for(String pluginName : pluginListEnabled)
{
if((AgentEngine.pluginMap.containsKey(pluginName)) && !pluginListActive.contains(pluginName))
{
PluginInterface pi = pluginMap.get(pluginName);
sb.append("Plugin: [" + pluginName + "] Name: " + AgentEngine.pluginsconfig.getPluginName(pluginName) + " Initialized: " + pi.getVersion() + "\n");
}
}
for(String pluginName : pluginListActive)
{
PluginInterface pi = pluginMap.get(pluginName);
sb.append("Plugin: [" + pluginName + "] Name: " + AgentEngine.pluginsconfig.getPluginName(pluginName) + " Initialized: " + pi.getVersion() + "\n");
}
if(pluginListDisabled.size() > 0)
{
sb.append("Disabled Plugins:\n");
}
for(String pluginName : pluginListDisabled)
{
if(!pluginListActive.contains(pluginName))
{
sb.append("Plugin: [" + pluginName + "] Name: " + AgentEngine.pluginsconfig.getPluginName(pluginName) + "\n");
}
}
}
else
{
sb.append("No Plugins Found!\n");
}
return sb.toString().substring(0,sb.toString().length()-1);
}
static List<String> getActivePlugins()
{
List<String> pluginList = new ArrayList<String>();
if(pluginMap != null)
{
Iterator it = pluginMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
String plugin = pairs.getKey().toString();
//disablePlugin(plugin,false);
pluginList.add(plugin);
//it.remove(); // avoids a ConcurrentModificationException
}
}
return pluginList;
}
static void cleanup() throws ConfigurationException, IOException, InterruptedException
{
System.out.println("Shutdown:Cleaning Active Agent Resources");
wd.timer.cancel();
List<String> pluginList = getActivePlugins();
/*
for(String plugin : pluginList)
{
if(((isController) && (plugin.equals(channelPluginSlot))))
{
}
else
{
//disablePlugin(plugin,false);
}
}
*/
/*
if(pluginMap != null)
{
Iterator it = pluginMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
String plugin = pairs.getKey().toString();
disablePlugin(plugin,false);
it.remove(); // avoids a ConcurrentModificationException
}
}
*/
if(!isRegionalController)
{
for(String plugin : pluginList)
{
if(!plugin.equals(channelPluginSlot))
{
disablePlugin(plugin,false);
}
}
if(msgInQueue != null)
{
MsgEvent de = clog.getLog("disabled");
de.setMsgType(MsgEventType.CONFIG);
de.setMsgAgent(AgentEngine.agent); //route to this agent
de.setMsgPlugin(AgentEngine.channelPluginSlot); //route to controller plugin
de.setParam("src_region",region);
de.setParam("src_agent",agent);
de.setParam("dst_region",region);
AgentEngine.commandExec.cmdExec(de);
Thread.sleep(5000);
disablePlugin(channelPluginSlot,false);
/*
int time = 0;
int timeout = 30; //give 30sec to timeout from RPC request
if(MsgInQueueThread != null)
{
//disablePlugin(controllerPluginSlot,false);
//disablePlugin(controllerPluginSlot,false);
disablePlugin(channelPluginSlot,false);
while((MsgInQueueThread.isAlive()) && (time < timeout))
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
time++;
}
}
*/
}
}
else
{
//cleanup controller here
for(String plugin : pluginList)
{
disablePlugin(plugin,false);
}
}
}
}
| create startup delay
| src/main/java/core/AgentEngine.java | create startup delay | <ide><path>rc/main/java/core/AgentEngine.java
<ide> processPlugins();
<ide> //and launch static plugins
<ide> //enableStaticPlugins()
<del>
<del>
<add>
<add> //delay and waiting for network init.
<add> int startupdelay = Integer.parseInt(config.getParams("general", "startupdelay"));
<add> Thread.sleep(startupdelay);
<add>
<ide> LoadControllerPlugin();
<ide>
<ide> isActive = true; |
|
JavaScript | mit | eb2ef7c018a5dbba0bd8bd42dd6829bbd16b5b65 | 0 | benlower/tableau-wdc-kcfoodinspection,benlower/tableau-wdc-kcfoodinspection | (function () {
// -------------------------------------------------- //
// WDC-specific things
// -------------------------------------------------- //
var myConnector = tableau.makeConnector();
myConnector.init = function () {
tableau.initCallback();
};
myConnector.getColumnHeaders = function () {
tableau.log('getColumnHeaders...');
var fieldNames = ['inspection_result', 'inspection_business_name', 'zip_code', 'inspection_score', 'inspection_type', 'violation_description', 'violation_record_id', 'inspection_closed_business', 'city', 'violation_type', 'inspection_date', 'inspection_serial_num', 'address', 'description', 'name', 'business_id', 'longitude', 'latitude', 'program_identifier', 'violation_points'];
var fieldTypes = ['string', 'string', 'string', 'int', 'string', 'string', 'string', 'bool', 'string', 'string', 'datetime', 'string', 'string', 'string', 'string', 'string', 'float', 'float', 'string', 'int'];
tableau.headersCallback(fieldNames, fieldTypes);
};
myConnector.getTableData = function () {
var zipCode = tableau.connectionData;
var url = 'https://data.kingcounty.gov/resource/f29f-zza5.json?zip_code=' + zipCode;
tableau.log('about to call ' + url);
$.getJSON(
url,
function(data, status) {
tableau.log("Request received: " + JSON.stringify(data));
}
);
// $.ajax({
// url: url,
// dataType: 'text',
// success: function (data) {
// if (data) {
// console.log('data: ' + data);
//
// // var i;
// // var toRet = [];
// //
// // for(i = 0; i < data.length; i++) {
// // var row = {
// // "inspection_result" : json[i]["inspection_result"] || null,
// // "inspection_business_name" : json[i]["inspection_business_name"] || null,
// // "zip_code" : json[i]["zip_code"] || null,
// // "inspection_score" : json[i]["inspection_score"] || null,
// // "inspection_type" : json[i]["inspection_type"] || null,
// // "violation_description" : json[i]["violation_description"] || null,
// // "violation_record_id" : json[i]["violation_record_id"] || null,
// // "inspection_closed_business" : json[i]["inspection_closed_business"] || null,
// // "city" : json[i]["city"] || null,
// // "violation_type" : json[i]["violation_type"] || null,
// // "inspection_date" : dateToTableauDate(json[i]["inspection_date"]) || null, // use a date format tableau knows
// // "inspection_serial_num" : json[i]["inspection_serial_num"] || null,
// // "address" : json[i]["address"] || null,
// // "description" : json[i]["description"] || null,
// // "name" : json[i]["name"] || null,
// // "business_id" : json[i]["business_id"] || null,
// // "longitude" : json[i]["longitude"] || null,
// // "latitude" : json[i]["latitude"] || null,
// // "program_identifier" : json[i]["program_identifier"] || null,
// // "violation_points" : json[i]["violation_points"] || null,
// //
// // };
// //
// // toRet.push(row);
// //
// // // Call back to tableau with the table data and the new record number (this is stored as a string)
// // tableau.dataCallback(toRet, toRet.length.toString(), false);
// } else {
// tableau.abortWithError("No results found for ticker symbol: " + ticker);
// }
// },
// error: function (xhr, ajaxOptions, thrownError) {
// // add something to the log and return an empty set if there was problem with the connection
// tableau.log("connection error: " + xhr.responseText + "\n" + thrownError);
// tableau.abortWithError("error connecting to the data source");
// }
// });
};
myConnector.setZipCode = function (zipCode) {
tableau.log("setting zip code to " + zipCode);
tableau.connectionData = zipCode;
tableau.connectionName = "King County Inspection Data: " + zipCode;
};
tableau.registerConnector(myConnector);
// Use Moment to convert dates to acceptible format for Tableau
function dateToTableauDate(dateToConvert) {
// Use moment
var moDate = moment(dateToConvert).format("YYYY-MM-DD HH:mm:ss.SSS");
return moDate;
}
$(document).ready(function () {
$("#getDataButton").click(function () {
console.log('button click');
var zipCode = $('#zipCode').val().trim();
tableau.log('zip code ' + zipCode);
// If we have a Zipcode then set it as tableau connection data so we can use it later
if (zipCode) {
myConnector.setZipCode(zipCode);
tableau.log('before calling submit(). tableau.phase: ' + tableau.phase);
tableau.submit();
}
});
});
})(); | javascripts/foodInspectionWDC.js | // Use Moment to convert dates to acceptible format for Tableau
function dateToTableauDate(dateToConvert) {
// Use moment
var moDate = moment(dateToConvert).format("YYYY-MM-DD HH:mm:ss.SSS");
return moDate;
}
$(document).ready(function() {
$("#getDataButton").click(function() {
var zipCode = $('#zipCode').val().trim();
console.log("zipCode: " + zipCode);
// If we have a Zipcode then set it as tableau connection data so we can use it later
if(zipCode) {
tableau.connectionData = zipCode;
tableau.connectionName = "King County Inspection Data: " + zipCode;
}
tableau.submit();
});
});
// -------------------------------------------------- //
// WDC-specific things
// -------------------------------------------------- //
var myConnector = tableau.makeConnector();
myConnector.init = function() {
tableau.initCallback();
};
myConnector.getColumnHeaders = function() {
var fieldNames = ['inspection_result', 'inspection_business_name', 'zip_code', 'inspection_score', 'inspection_type', 'violation_description', 'violation_record_id', 'inspection_closed_business', 'city', 'violation_type', 'inspection_date', 'inspection_serial_num', 'address', 'description', 'name', 'business_id', 'longitude', 'latitude', 'program_identifier', 'violation_points'];
var fieldTypes = ['string', 'string', 'string', 'int', 'string', 'string', 'string', 'bool', 'string', 'string', 'datetime', 'string', 'string', 'string', 'string', 'string', 'float', 'float', 'string', 'int'];
tableau.headersCallback(fieldNames, fieldTypes);
};
myConnector.getTableData = function() {
var zipCode = tableau.connectionData;
var url = 'https://data.kingcounty.gov/resource/f29f-zza5.json?zip_code=' + zipCode;
$.getJSON(url, function(json, status, xhr) {
if(json) {
console.log('our json: ' + JSON.stringify(json));
var i;
var toRet = [];
for(i = 0; i < json.length; i++) {
var row = {
"inspection_result" : json[i]["inspection_result"] || null,
"inspection_business_name" : json[i]["inspection_business_name"] || null,
"zip_code" : json[i]["zip_code"] || null,
"inspection_score" : json[i]["inspection_score"] || null,
"inspection_type" : json[i]["inspection_type"] || null,
"violation_description" : json[i]["violation_description"] || null,
"violation_record_id" : json[i]["violation_record_id"] || null,
"inspection_closed_business" : json[i]["inspection_closed_business"] || null,
"city" : json[i]["city"] || null,
"violation_type" : json[i]["violation_type"] || null,
"inspection_date" : dateToTableauDate(json[i]["inspection_date"]) || null, // use a date format tableau knows
"inspection_serial_num" : json[i]["inspection_serial_num"] || null,
"address" : json[i]["address"] || null,
"description" : json[i]["description"] || null,
"name" : json[i]["name"] || null,
"business_id" : json[i]["business_id"] || null,
"longitude" : json[i]["longitude"] || null,
"latitude" : json[i]["latitude"] || null,
"program_identifier" : json[i]["program_identifier"] || null,
"violation_points" : json[i]["violation_points"] || null,
};
toRet.push(row);
}
// call back to tableau with data
tableau.dataCallback(toRet, toRet.length.toString(), false);
} else {
console.log('error: ' + xhr.responseText);
tableau.abortWithError("error getting data");
}
});
};
tableau.registerConnector(myConnector); | debugging connection issues
getTableData() is only called if a breakpoint set on tableau.submit()
| javascripts/foodInspectionWDC.js | debugging connection issues | <ide><path>avascripts/foodInspectionWDC.js
<del>// Use Moment to convert dates to acceptible format for Tableau
<del>function dateToTableauDate(dateToConvert) {
<del> // Use moment
<del> var moDate = moment(dateToConvert).format("YYYY-MM-DD HH:mm:ss.SSS");
<del>
<del> return moDate;
<del>}
<del>
<del>$(document).ready(function() {
<del> $("#getDataButton").click(function() {
<del> var zipCode = $('#zipCode').val().trim();
<del> console.log("zipCode: " + zipCode);
<del>
<del> // If we have a Zipcode then set it as tableau connection data so we can use it later
<del> if(zipCode) {
<del> tableau.connectionData = zipCode;
<del> tableau.connectionName = "King County Inspection Data: " + zipCode;
<del> }
<del>
<del> tableau.submit();
<del> });
<del>});
<del>
<del>// -------------------------------------------------- //
<del>// WDC-specific things
<del>// -------------------------------------------------- //
<del>var myConnector = tableau.makeConnector();
<del>
<del>myConnector.init = function() {
<del> tableau.initCallback();
<del>};
<del>
<del>
<del>myConnector.getColumnHeaders = function() {
<del> var fieldNames = ['inspection_result', 'inspection_business_name', 'zip_code', 'inspection_score', 'inspection_type', 'violation_description', 'violation_record_id', 'inspection_closed_business', 'city', 'violation_type', 'inspection_date', 'inspection_serial_num', 'address', 'description', 'name', 'business_id', 'longitude', 'latitude', 'program_identifier', 'violation_points'];
<add> (function () {
<add> // -------------------------------------------------- //
<add> // WDC-specific things
<add> // -------------------------------------------------- //
<add> var myConnector = tableau.makeConnector();
<ide>
<del> var fieldTypes = ['string', 'string', 'string', 'int', 'string', 'string', 'string', 'bool', 'string', 'string', 'datetime', 'string', 'string', 'string', 'string', 'string', 'float', 'float', 'string', 'int'];
<del>
<del> tableau.headersCallback(fieldNames, fieldTypes);
<del>};
<del>
<del>myConnector.getTableData = function() {
<del> var zipCode = tableau.connectionData;
<del> var url = 'https://data.kingcounty.gov/resource/f29f-zza5.json?zip_code=' + zipCode;
<del>
<del> $.getJSON(url, function(json, status, xhr) {
<del> if(json) {
<del> console.log('our json: ' + JSON.stringify(json));
<del>
<del> var i;
<del> var toRet = [];
<del>
<del> for(i = 0; i < json.length; i++) {
<del> var row = {
<del> "inspection_result" : json[i]["inspection_result"] || null,
<del> "inspection_business_name" : json[i]["inspection_business_name"] || null,
<del> "zip_code" : json[i]["zip_code"] || null,
<del> "inspection_score" : json[i]["inspection_score"] || null,
<del> "inspection_type" : json[i]["inspection_type"] || null,
<del> "violation_description" : json[i]["violation_description"] || null,
<del> "violation_record_id" : json[i]["violation_record_id"] || null,
<del> "inspection_closed_business" : json[i]["inspection_closed_business"] || null,
<del> "city" : json[i]["city"] || null,
<del> "violation_type" : json[i]["violation_type"] || null,
<del> "inspection_date" : dateToTableauDate(json[i]["inspection_date"]) || null, // use a date format tableau knows
<del> "inspection_serial_num" : json[i]["inspection_serial_num"] || null,
<del> "address" : json[i]["address"] || null,
<del> "description" : json[i]["description"] || null,
<del> "name" : json[i]["name"] || null,
<del> "business_id" : json[i]["business_id"] || null,
<del> "longitude" : json[i]["longitude"] || null,
<del> "latitude" : json[i]["latitude"] || null,
<del> "program_identifier" : json[i]["program_identifier"] || null,
<del> "violation_points" : json[i]["violation_points"] || null,
<del>
<del> };
<del>
<del> toRet.push(row);
<del> }
<del>
<del> // call back to tableau with data
<del> tableau.dataCallback(toRet, toRet.length.toString(), false);
<del>
<del> } else {
<del> console.log('error: ' + xhr.responseText);
<del> tableau.abortWithError("error getting data");
<del> }
<del> });
<del>
<del>};
<del>
<del>
<del>tableau.registerConnector(myConnector);
<add> myConnector.init = function () {
<add> tableau.initCallback();
<add> };
<add>
<add>
<add> myConnector.getColumnHeaders = function () {
<add> tableau.log('getColumnHeaders...');
<add> var fieldNames = ['inspection_result', 'inspection_business_name', 'zip_code', 'inspection_score', 'inspection_type', 'violation_description', 'violation_record_id', 'inspection_closed_business', 'city', 'violation_type', 'inspection_date', 'inspection_serial_num', 'address', 'description', 'name', 'business_id', 'longitude', 'latitude', 'program_identifier', 'violation_points'];
<add>
<add> var fieldTypes = ['string', 'string', 'string', 'int', 'string', 'string', 'string', 'bool', 'string', 'string', 'datetime', 'string', 'string', 'string', 'string', 'string', 'float', 'float', 'string', 'int'];
<add>
<add> tableau.headersCallback(fieldNames, fieldTypes);
<add> };
<add>
<add> myConnector.getTableData = function () {
<add> var zipCode = tableau.connectionData;
<add> var url = 'https://data.kingcounty.gov/resource/f29f-zza5.json?zip_code=' + zipCode;
<add>
<add> tableau.log('about to call ' + url);
<add>
<add> $.getJSON(
<add> url,
<add> function(data, status) {
<add> tableau.log("Request received: " + JSON.stringify(data));
<add> }
<add> );
<add> // $.ajax({
<add> // url: url,
<add> // dataType: 'text',
<add> // success: function (data) {
<add> // if (data) {
<add> // console.log('data: ' + data);
<add> //
<add> // // var i;
<add> // // var toRet = [];
<add> // //
<add> // // for(i = 0; i < data.length; i++) {
<add> // // var row = {
<add> // // "inspection_result" : json[i]["inspection_result"] || null,
<add> // // "inspection_business_name" : json[i]["inspection_business_name"] || null,
<add> // // "zip_code" : json[i]["zip_code"] || null,
<add> // // "inspection_score" : json[i]["inspection_score"] || null,
<add> // // "inspection_type" : json[i]["inspection_type"] || null,
<add> // // "violation_description" : json[i]["violation_description"] || null,
<add> // // "violation_record_id" : json[i]["violation_record_id"] || null,
<add> // // "inspection_closed_business" : json[i]["inspection_closed_business"] || null,
<add> // // "city" : json[i]["city"] || null,
<add> // // "violation_type" : json[i]["violation_type"] || null,
<add> // // "inspection_date" : dateToTableauDate(json[i]["inspection_date"]) || null, // use a date format tableau knows
<add> // // "inspection_serial_num" : json[i]["inspection_serial_num"] || null,
<add> // // "address" : json[i]["address"] || null,
<add> // // "description" : json[i]["description"] || null,
<add> // // "name" : json[i]["name"] || null,
<add> // // "business_id" : json[i]["business_id"] || null,
<add> // // "longitude" : json[i]["longitude"] || null,
<add> // // "latitude" : json[i]["latitude"] || null,
<add> // // "program_identifier" : json[i]["program_identifier"] || null,
<add> // // "violation_points" : json[i]["violation_points"] || null,
<add> // //
<add> // // };
<add> // //
<add> // // toRet.push(row);
<add> // //
<add> // // // Call back to tableau with the table data and the new record number (this is stored as a string)
<add> // // tableau.dataCallback(toRet, toRet.length.toString(), false);
<add> // } else {
<add> // tableau.abortWithError("No results found for ticker symbol: " + ticker);
<add> // }
<add> // },
<add> // error: function (xhr, ajaxOptions, thrownError) {
<add> // // add something to the log and return an empty set if there was problem with the connection
<add> // tableau.log("connection error: " + xhr.responseText + "\n" + thrownError);
<add> // tableau.abortWithError("error connecting to the data source");
<add> // }
<add> // });
<add>
<add> };
<add>
<add> myConnector.setZipCode = function (zipCode) {
<add> tableau.log("setting zip code to " + zipCode);
<add> tableau.connectionData = zipCode;
<add> tableau.connectionName = "King County Inspection Data: " + zipCode;
<add> };
<add>
<add> tableau.registerConnector(myConnector);
<add>
<add> // Use Moment to convert dates to acceptible format for Tableau
<add> function dateToTableauDate(dateToConvert) {
<add> // Use moment
<add> var moDate = moment(dateToConvert).format("YYYY-MM-DD HH:mm:ss.SSS");
<add>
<add> return moDate;
<add> }
<add>
<add> $(document).ready(function () {
<add> $("#getDataButton").click(function () {
<add> console.log('button click');
<add> var zipCode = $('#zipCode').val().trim();
<add> tableau.log('zip code ' + zipCode);
<add>
<add> // If we have a Zipcode then set it as tableau connection data so we can use it later
<add> if (zipCode) {
<add> myConnector.setZipCode(zipCode);
<add> tableau.log('before calling submit(). tableau.phase: ' + tableau.phase);
<add> tableau.submit();
<add> }
<add> });
<add> });
<add> })(); |
|
Java | apache-2.0 | 1087b1a2f96ee912146aab65bbc4253221b955b3 | 0 | ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma | /*
* The Gemma project
*
* Copyright (c) 2006 University of British Columbia
*
* 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 ubic.gemma.web.controller.coexpressionSearch;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import ubic.gemma.loader.genome.taxon.SupportedTaxa;
import ubic.gemma.model.association.Gene2GOAssociationService;
import ubic.gemma.model.coexpression.CoexpressionCollectionValueObject;
import ubic.gemma.model.coexpression.CoexpressionValueObject;
import ubic.gemma.model.common.description.OntologyEntry;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.expression.experiment.ExpressionExperimentService;
import ubic.gemma.model.expression.experiment.ExpressionExperimentValueObject;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.model.genome.Taxon;
import ubic.gemma.model.genome.TaxonService;
import ubic.gemma.model.genome.gene.GeneService;
import ubic.gemma.search.SearchService;
import ubic.gemma.util.progress.ProgressJob;
import ubic.gemma.util.progress.ProgressManager;
import ubic.gemma.web.controller.BackgroundControllerJob;
import ubic.gemma.web.controller.BackgroundProcessingFormBindController;
import ubic.gemma.web.propertyeditor.TaxonPropertyEditor;
import ubic.gemma.web.util.ConfigurationCookie;
import ubic.gemma.web.util.MessageUtil;
/**
* A <link>SimpleFormController<link> providing search functionality of genes or design elements (probe sets). The
* success view returns either a visual representation of the result set or a downloadable data file.
* <p>
* {@link stringency} sets the number of data sets the link must be seen in before it is listed in the results, and
* {@link species} sets the type of species to search. {@link keywords} restrict the search.
*
* @author keshav
* @version $Id$
* @spring.bean id="coexpressionSearchController"
* @spring.property name = "commandName" value="coexpressionSearchCommand"
* @spring.property name = "commandClass" value="ubic.gemma.web.controller.coexpressionSearch.CoexpressionSearchCommand"
* @spring.property name = "formView" value="searchCoexpression"
* @spring.property name = "successView" value="searchCoexpression"
* @spring.property name = "geneService" ref="geneService"
* @spring.property name = "taxonService" ref="taxonService"
* @spring.property name = "searchService" ref="searchService"
* @spring.property name = "expressionExperimentService" ref="expressionExperimentService"
* @spring.property name = "gene2GOAssociationService" ref="gene2GOAssociationService"
* @spring.property name = "validator" ref="genericBeanValidator"
*/
public class CoexpressionSearchController extends BackgroundProcessingFormBindController {
private static Log log = LogFactory.getLog( CoexpressionSearchController.class.getName() );
private int MAX_GENES_TO_RETURN = 50;
private int DEFAULT_STRINGENCY = 3;
private static final String COOKIE_NAME = "coexpressionSearchCookie";
private GeneService geneService = null;
private TaxonService taxonService = null;
private SearchService searchService = null;
private ExpressionExperimentService expressionExperimentService = null;
private Gene2GOAssociationService gene2GOAssociationService;
public CoexpressionSearchController() {
/*
* if true, reuses the same command object across the edit-submit-process (get-post-process).
*/
setSessionForm( true );
}
/**
* @param request
* @return Object
* @throws ServletException
*/
@Override
protected Object formBackingObject( HttpServletRequest request ) {
CoexpressionSearchCommand csc = new CoexpressionSearchCommand();
if ( request.getParameter( "searchString" ) != null ) {
loadGETParameters( request, csc );
} else {
loadCookie( request, csc );
}
return csc;
}
/**
* Mock function - do not use.
*
* @param request
* @param response
* @param command
* @param errors
* @return ModelAndView
* @throws Exception
*/
@SuppressWarnings( { "unused", "unchecked" })
@Override
public ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command,
BindException errors ) throws Exception {
CoexpressionSearchCommand csc = ( ( CoexpressionSearchCommand ) command );
Cookie cookie = new CoexpressionSearchCookie( csc );
response.addCookie( cookie );
Collection<Gene> genesFound;
// find the genes specified by the search
// if there is no exact search specified, do an inexact search
// if exact search is on, find only by official symbol
// if exact search is auto (usually from the front page), check if there is an exact search match. If there is
// none, do inexact search.
if ( csc.getExactSearch() == null ) {
genesFound = searchService.geneDbSearch( csc.getSearchString() );
genesFound.addAll( searchService.compassGeneSearch( csc.getSearchString() ) );
} else if ( csc.getGeneIdSearch().equalsIgnoreCase( "true" ) ) {
String geneId = csc.getSearchString();
Long id = Long.parseLong( geneId );
Collection<Long> ids = new ArrayList<Long>();
ids.add( id );
genesFound = geneService.load( ids );
} else if ( csc.getExactSearch().equalsIgnoreCase( "on" ) ) {
genesFound = geneService.findByOfficialSymbol( csc.getSearchString() );
} else {
genesFound = geneService.findByOfficialSymbol( csc.getSearchString() );
if ( genesFound.size() == 0 ) {
genesFound = searchService.geneDbSearch( csc.getSearchString() );
genesFound.addAll( searchService.compassGeneSearch( csc.getSearchString() ) );
}
}
// filter genes by Taxon
Collection<Gene> genesToRemove = new ArrayList<Gene>();
if ( ( csc.getTaxon() != null ) && ( csc.getTaxon().getId() != null ) ) {
for ( Gene gene : genesFound ) {
if ( gene.getTaxon().getId().longValue() != csc.getTaxon().getId().longValue() ) {
genesToRemove.add( gene );
}
}
genesFound.removeAll( genesToRemove );
}
// if no genes found
// return error
if ( genesFound.size() == 0 ) {
saveMessage( request, "No genes found based on criteria." );
return super.showForm( request, response, errors );
}
// check if more than 1 gene found
// if yes, then query user for gene to be used
if ( genesFound.size() > 1 ) {
// check if more than 50 genes have been found.
// if there are more, then warn the user and truncate list
if ( genesFound.size() > MAX_GENES_TO_RETURN ) {
genesToRemove = new ArrayList<Gene>();
int count = 0;
for ( Gene gene : genesFound ) {
if ( count >= MAX_GENES_TO_RETURN ) {
genesToRemove.add( gene );
}
count++;
}
genesFound.removeAll( genesToRemove );
saveMessage( request, "Found " + count + " genes. Truncating list to first " + MAX_GENES_TO_RETURN
+ "." );
}
saveMessage( request, "Multiple genes matched. Choose which gene to use." );
// set to exact search
csc.setExactSearch( "on" );
ModelAndView mav = super.showForm( request, errors, getFormView() );
mav.addObject( "genes", genesFound );
return mav;
}
// At this point, only one gene has been found
// set command object to reflect this
csc.setSearchString( genesFound.iterator().next().getOfficialSymbol() );
csc.setGeneIdSearch( "false" );
// find coexpressed genes
// find expressionExperiments via lucene if the query is eestring-constrained
Collection<ExpressionExperiment> ees;
if ( StringUtils.isNotBlank( csc.getEeSearchString() ) ) {
ees = searchService.compassExpressionSearch( csc.getEeSearchString() );
if ( ees.size() == 0 ) {
saveMessage( request, "No datasets matched - defaulting to all datasets" );
}
} else {
ees = new ArrayList<ExpressionExperiment>();
}
Gene sourceGene = ( Gene ) ( genesFound.toArray() )[0];
csc.setSourceGene( sourceGene );
Integer numExpressionExperiments = 0;
Collection<Long> possibleEEs = expressionExperimentService.findByGene( sourceGene );
if ((ees == null) || (ees.isEmpty()) ){
ModelAndView mav = super.showForm( request, errors, getFormView() );
saveMessage( request, "There are no " + csc.getTaxon().getScientificName() + " arrays in the system that assay for the gene " + csc.getSourceGene().getOfficialSymbol() );
return mav;
}
else if ( ees.size() > 0 ) {
// if there are matches, fihter the expression experiments first by taxon
Collection<ExpressionExperiment> eeToRemove = new HashSet<ExpressionExperiment>();
for ( ExpressionExperiment ee : ees ) {
Taxon t = expressionExperimentService.getTaxon( ee.getId() );
if ( t.getId().longValue() != csc.getTaxon().getId().longValue() ) eeToRemove.add( ee );
if ( !possibleEEs.contains( ee.getId() ) ) eeToRemove.add( ee );
}
ees.removeAll( eeToRemove );
} else
ees = expressionExperimentService.load( possibleEEs );
csc.setToUseEE( ees );
numExpressionExperiments = ees.size();
// stringency. Cannot be less than 1; set to one if it is
Integer stringency = csc.getStringency();
if ( stringency == null ) {
stringency = DEFAULT_STRINGENCY;
} else if ( stringency < 1 ) {
stringency = DEFAULT_STRINGENCY;
}
csc.setStringency( stringency );
return startJob( command, request, response, errors );
}
/**
* @param request
* @return Map
*/
@SuppressWarnings("unused")
@Override
protected Map referenceData( HttpServletRequest request ) {
Map<String, List<? extends Object>> mapping = new HashMap<String, List<? extends Object>>();
// add species
populateTaxonReferenceData( mapping );
return mapping;
}
/**
* @param mapping
*/
@SuppressWarnings("unchecked")
private void populateTaxonReferenceData( Map mapping ) {
List<Taxon> taxa = new ArrayList<Taxon>();
for ( Taxon taxon : ( Collection<Taxon> ) taxonService.loadAll() ) {
if ( !SupportedTaxa.contains( taxon ) ) {
continue;
}
taxa.add( taxon );
}
Collections.sort( taxa, new Comparator<Taxon>() {
public int compare( Taxon o1, Taxon o2 ) {
return ( o1 ).getScientificName().compareTo( ( o2 ).getScientificName() );
}
} );
mapping.put( "taxa", taxa );
}
@Override
protected void initBinder( HttpServletRequest request, ServletRequestDataBinder binder ) {
super.initBinder( request, binder );
binder.registerCustomEditor( Taxon.class, new TaxonPropertyEditor( this.taxonService ) );
}
/**
* @param request
* @param csc
*/
private void loadCookie( HttpServletRequest request, CoexpressionSearchCommand csc ) {
// cookies aren't all that important, if they're missing we just go on.
if ( request == null || request.getCookies() == null ) return;
for ( Cookie cook : request.getCookies() ) {
if ( cook.getName().equals( COOKIE_NAME ) ) {
try {
ConfigurationCookie cookie = new ConfigurationCookie( cook );
csc.setEeSearchString( cookie.getString( "eeSearchString" ) );
csc.setStringency( cookie.getInt( "stringency" ) );
Taxon taxon = taxonService.findByScientificName( cookie.getString( "taxonScientificName" ) );
csc.setTaxon( taxon );
// save the gene name. If the gene id is on, then convert the ID to a gene first
String searchString = cookie.getString( "searchString" );
csc.setSearchString( searchString );
} catch ( Exception e ) {
log.warn( "Cookie could not be loaded: " + e.getMessage() );
// that's okay, we just don't get a cookie.
}
}
}
}
/**
* Fills in the command object in the case that GET parameters are passed in
*
* @param request
* @param csc
*/
private void loadGETParameters( HttpServletRequest request, CoexpressionSearchCommand csc ) {
if ( request == null || ( request.getParameter( "searchString" ) == null ) ) return;
Map params = request.getParameterMap();
if ( params.get( "eeSearchString" ) != null ) {
csc.setEeSearchString( ( ( String[] ) params.get( "eeSearchString" ) )[0] );
}
if ( params.get( "geneIdSearch" ) != null ) {
String[] geneIdSearch = ( String[] ) params.get( "geneIdSearch" );
csc.setGeneIdSearch( geneIdSearch[0] );
}
if ( params.get( "stringency" ) != null ) {
String[] stringency = ( String[] ) params.get( "stringency" );
Integer num = Integer.parseInt( stringency[0] );
csc.setStringency( num );
}
if ( params.get( "taxon" ) != null ) {
Taxon taxon = taxonService.findByScientificName( ( ( String[] ) params.get( "taxon" ) )[0] );
csc.setTaxon( taxon );
}
if ( params.get( "searchString" ) != null ) {
String searchString = ( ( String[] ) params.get( "searchString" ) )[0];
csc.setSearchString( searchString );
}
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.mvc.SimpleFormController#showForm(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, org.springframework.validation.BindException)
*/
protected ModelAndView showForm( HttpServletRequest request, HttpServletResponse response, BindException errors )
throws Exception {
if ( request.getParameter( "searchString" ) != null ) {
return this.onSubmit( request, response, this.formBackingObject( request ), errors );
}
return super.showForm( request, response, errors );
}
/**
* @param geneService
*/
public void setGeneService( GeneService geneService ) {
this.geneService = geneService;
}
/**
* @param taxonService the taxonService to set
*/
public void setTaxonService( TaxonService taxonService ) {
this.taxonService = taxonService;
}
/**
* @param searchService the searchService to set
*/
public void setSearchService( SearchService searchService ) {
this.searchService = searchService;
}
/**
* @param expressionExperimentService the expressionExperimentService to set
*/
public void setExpressionExperimentService( ExpressionExperimentService expressionExperimentService ) {
this.expressionExperimentService = expressionExperimentService;
}
@Override
protected BackgroundControllerJob<ModelAndView> getRunner( String taskId, SecurityContext securityContext,
final HttpServletRequest request, final HttpServletResponse response, final Object command,
final MessageUtil messenger, final BindException errors ) {
return new BackgroundControllerJob<ModelAndView>( taskId, securityContext, request, response, command,
messenger, errors ) {
@SuppressWarnings("unchecked")
public ModelAndView call() throws Exception {
SecurityContextHolder.setContext( securityContext );
CoexpressionSearchCommand csc = ( CoexpressionSearchCommand ) command;
ProgressJob job = ProgressManager.createProgressJob( this.getTaskId(), securityContext
.getAuthentication().getName(), "Coexpression analysis for "
+ csc.getSourceGene().getOfficialSymbol() );
job.updateProgress( "Analyzing coexpresson for " + csc.getSourceGene().getOfficialSymbol() );
CoexpressionCollectionValueObject coexpressions = ( CoexpressionCollectionValueObject ) geneService
.getCoexpressedGenes( csc.getSourceGene(), csc.getToUseEE(), csc.getStringency() );
StopWatch watch = new StopWatch();
watch.start();
// get all the coexpressed genes and sort them by dataset count
List<CoexpressionValueObject> coexpressedGenes = new ArrayList<CoexpressionValueObject>();
coexpressedGenes.addAll( coexpressions.getCoexpressionData() );
// sort coexpressed genes by dataset count
Collections.sort( coexpressedGenes, new CoexpressionComparator() );
// calculate the goOverlap for the 1st 100 genes
int i = 0;
Collection<Long> overlapIds = new HashSet<Long>();
for ( CoexpressionValueObject cvo : coexpressedGenes ) {
i++;
if ( i >= 25 ) break;
overlapIds.add( cvo.getGeneId() );
}
Map<Long,Collection<OntologyEntry>> overlap = gene2GOAssociationService.calculateGoTermOverlap( csc.getSourceGene(), overlapIds );
for ( CoexpressionValueObject cvo : coexpressedGenes ){
cvo.setGoOverlap( overlap.get( cvo.getGeneId() ) );
}
// load expression experiment value objects
Collection<Long> eeIds = new HashSet<Long>();
Collection<ExpressionExperimentValueObject> origEeVos = coexpressions.getExpressionExperiments();
for ( ExpressionExperimentValueObject eeVo : origEeVos ) {
eeIds.add( eeVo.getId() );
}
Collection<ExpressionExperimentValueObject> eeVos = expressionExperimentService
.loadValueObjects( eeIds );
// add link count information to ee value objects
// coexpressions.calculateLinkCounts();
// coexpressions.calculateRawLinkCounts();
for ( ExpressionExperimentValueObject eeVo : eeVos ) {
eeVo.setCoexpressionLinkCount( coexpressions.getLinkCountForEE( eeVo.getId() ) );
eeVo.setRawCoexpressionLinkCount( coexpressions.getRawLinkCountForEE( eeVo.getId() ) );
}
// new ModelAndView(getSuccessView());
// no genes are coexpressed
// return error
if ( coexpressedGenes.size() == 0 ) {
this.saveMessage( "No genes are coexpressed with the given stringency." );
}
Long numUsedExpressionExperiments = new Long( coexpressions.getNumberOfUsedExpressonExperiments() );
Long numPositiveCoexpressedGenes = new Long( coexpressions.getPositiveStringencyLinkCount() );
Long numNegativeCoexpressedGenes = new Long( coexpressions.getNegativeStringencyLinkCount() );
Long numGenes = new Long( coexpressions.getNumGenes() );
Long numPredictedGenes = new Long( coexpressions.getNumPredictedGenes() );
Long numProbeAlignedRegions = new Long( coexpressions.getNumProbeAlignedRegions() );
Long numStringencyGenes = new Long( coexpressions.getNumStringencyGenes() );
Long numStringencyPredictedGenes = new Long( coexpressions.getNumStringencyPredictedGenes() );
Long numStringencyProbeAlignedRegions = new Long( coexpressions.getNumStringencyProbeAlignedRegions() );
Integer numMatchedLinks = coexpressions.getLinkCount();
// addTimingInformation( request, coexpressions );
job.updateProgress( "ending...." );
ProgressManager.destroyProgressJob( job );
// request.getParameterMap().remove( "searchString" );
// request.setAttribute( "inner", "inner" );
ModelAndView mav = new ModelAndView( getSuccessView() );
// mav.setViewName( getSuccessView() );
mav.addObject( "coexpressedGenes", coexpressedGenes );
mav.addObject( "numPositiveCoexpressedGenes", numPositiveCoexpressedGenes );
mav.addObject( "numNegativeCoexpressedGenes", numNegativeCoexpressedGenes );
mav.addObject( "numSearchedExpressionExperiments", csc.getToUseEE().size() );
mav.addObject( "numUsedExpressionExperiments", numUsedExpressionExperiments );
mav.addObject( "numGenes", numGenes );
mav.addObject( "numPredictedGenes", numPredictedGenes );
mav.addObject( "numProbeAlignedRegions", numProbeAlignedRegions );
mav.addObject( "numStringencyGenes", numStringencyGenes );
mav.addObject( "numStringencyPredictedGenes", numStringencyPredictedGenes );
mav.addObject( "numStringencyProbeAlignedRegions", numStringencyProbeAlignedRegions );
mav.addObject( "numMatchedLinks", numMatchedLinks );
mav.addObject( "sourceGene", csc.getSourceGene() );
mav.addObject( "expressionExperiments", eeVos );
mav.addObject( "numLinkedExpressionExperiments", new Integer( eeVos.size() ) );
// binding objects
mav.addObject( "coexpressionSearchCommand", csc );
populateTaxonReferenceData( mav.getModel() );
mav.addAllObjects( errors.getModel() );
Long elapsed = watch.getTime();
watch.stop();
log.info( "Processing after DAO call (elapsed time): " + elapsed );
this.saveMessage( "Coexpression query took: " + coexpressions.getElapsedWallSeconds() );
return mav;
}
};
}
class CoexpressionSearchCookie extends ConfigurationCookie {
public CoexpressionSearchCookie( CoexpressionSearchCommand command ) {
super( COOKIE_NAME );
this.setProperty( "eeSearchString", command.getEeSearchString() );
// save the gene name. If the gene id is on, then convert the ID to a gene first
if ( !StringUtils.isBlank( command.getGeneIdSearch() ) ) {
String geneId = command.getSearchString();
Long id;
try {
id = Long.parseLong( geneId );
Gene g = geneService.load( id );
this.setProperty( "searchString", g.getOfficialSymbol() );
} catch ( NumberFormatException e ) {
this.setProperty( "searchString", command.getSearchString() );
}
} else {
this.setProperty( "searchString", command.getSearchString() );
}
this.setProperty( "stringency", command.getStringency() );
this.setProperty( "taxonScientificName", command.getTaxon().getScientificName() );
this.setMaxAge( 100000 );
this.setComment( "Information for coexpression search form" );
}
}
/**
* @author jsantos
*/
class CoexpressionComparator implements Comparator {
public int compare( Object o1, Object o2 ) {
CoexpressionValueObject v1 = ( ( CoexpressionValueObject ) o1 );
CoexpressionValueObject v2 = ( ( CoexpressionValueObject ) o2 );
int o1Size = v1.getExpressionExperimentValueObjects().size();
int o2Size = v2.getExpressionExperimentValueObjects().size();
if ( o1Size > o2Size ) {
return -1;
} else if ( o1Size < o2Size ) {
return 1;
} else {
return 0;
// return v2.getGeneId().compareTo( v1.getGeneId() );
}
}
}
public Gene2GOAssociationService getGene2GOAssociationService() {
return gene2GOAssociationService;
}
public void setGene2GOAssociationService( Gene2GOAssociationService gene2GOAssociationService ) {
this.gene2GOAssociationService = gene2GOAssociationService;
}
} | gemma-web/src/main/java/ubic/gemma/web/controller/coexpressionSearch/CoexpressionSearchController.java | /*
* The Gemma project
*
* Copyright (c) 2006 University of British Columbia
*
* 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 ubic.gemma.web.controller.coexpressionSearch;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import ubic.gemma.loader.genome.taxon.SupportedTaxa;
import ubic.gemma.model.association.Gene2GOAssociationService;
import ubic.gemma.model.coexpression.CoexpressionCollectionValueObject;
import ubic.gemma.model.coexpression.CoexpressionValueObject;
import ubic.gemma.model.common.description.OntologyEntry;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.expression.experiment.ExpressionExperimentService;
import ubic.gemma.model.expression.experiment.ExpressionExperimentValueObject;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.model.genome.Taxon;
import ubic.gemma.model.genome.TaxonService;
import ubic.gemma.model.genome.gene.GeneService;
import ubic.gemma.search.SearchService;
import ubic.gemma.util.progress.ProgressJob;
import ubic.gemma.util.progress.ProgressManager;
import ubic.gemma.web.controller.BackgroundControllerJob;
import ubic.gemma.web.controller.BackgroundProcessingFormBindController;
import ubic.gemma.web.propertyeditor.TaxonPropertyEditor;
import ubic.gemma.web.util.ConfigurationCookie;
import ubic.gemma.web.util.MessageUtil;
/**
* A <link>SimpleFormController<link> providing search functionality of genes or design elements (probe sets). The
* success view returns either a visual representation of the result set or a downloadable data file.
* <p>
* {@link stringency} sets the number of data sets the link must be seen in before it is listed in the results, and
* {@link species} sets the type of species to search. {@link keywords} restrict the search.
*
* @author keshav
* @version $Id$
* @spring.bean id="coexpressionSearchController"
* @spring.property name = "commandName" value="coexpressionSearchCommand"
* @spring.property name = "commandClass" value="ubic.gemma.web.controller.coexpressionSearch.CoexpressionSearchCommand"
* @spring.property name = "formView" value="searchCoexpression"
* @spring.property name = "successView" value="searchCoexpression"
* @spring.property name = "geneService" ref="geneService"
* @spring.property name = "taxonService" ref="taxonService"
* @spring.property name = "searchService" ref="searchService"
* @spring.property name = "expressionExperimentService" ref="expressionExperimentService"
* @spring.property name = "gene2GOAssociationService" ref="gene2GOAssociationService"
* @spring.property name = "validator" ref="genericBeanValidator"
*/
public class CoexpressionSearchController extends BackgroundProcessingFormBindController {
private static Log log = LogFactory.getLog( CoexpressionSearchController.class.getName() );
private int MAX_GENES_TO_RETURN = 50;
private int DEFAULT_STRINGENCY = 3;
private static final String COOKIE_NAME = "coexpressionSearchCookie";
private GeneService geneService = null;
private TaxonService taxonService = null;
private SearchService searchService = null;
private ExpressionExperimentService expressionExperimentService = null;
private Gene2GOAssociationService gene2GOAssociationService;
public CoexpressionSearchController() {
/*
* if true, reuses the same command object across the edit-submit-process (get-post-process).
*/
setSessionForm( true );
}
/**
* @param request
* @return Object
* @throws ServletException
*/
@Override
protected Object formBackingObject( HttpServletRequest request ) {
CoexpressionSearchCommand csc = new CoexpressionSearchCommand();
if ( request.getParameter( "searchString" ) != null ) {
loadGETParameters( request, csc );
} else {
loadCookie( request, csc );
}
return csc;
}
/**
* Mock function - do not use.
*
* @param request
* @param response
* @param command
* @param errors
* @return ModelAndView
* @throws Exception
*/
@SuppressWarnings( { "unused", "unchecked" })
@Override
public ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command,
BindException errors ) throws Exception {
CoexpressionSearchCommand csc = ( ( CoexpressionSearchCommand ) command );
Cookie cookie = new CoexpressionSearchCookie( csc );
response.addCookie( cookie );
Collection<Gene> genesFound;
// find the genes specified by the search
// if there is no exact search specified, do an inexact search
// if exact search is on, find only by official symbol
// if exact search is auto (usually from the front page), check if there is an exact search match. If there is
// none, do inexact search.
if ( csc.getExactSearch() == null ) {
genesFound = searchService.geneDbSearch( csc.getSearchString() );
genesFound.addAll( searchService.compassGeneSearch( csc.getSearchString() ) );
} else if ( csc.getGeneIdSearch().equalsIgnoreCase( "true" ) ) {
String geneId = csc.getSearchString();
Long id = Long.parseLong( geneId );
Collection<Long> ids = new ArrayList<Long>();
ids.add( id );
genesFound = geneService.load( ids );
} else if ( csc.getExactSearch().equalsIgnoreCase( "on" ) ) {
genesFound = geneService.findByOfficialSymbol( csc.getSearchString() );
} else {
genesFound = geneService.findByOfficialSymbol( csc.getSearchString() );
if ( genesFound.size() == 0 ) {
genesFound = searchService.geneDbSearch( csc.getSearchString() );
genesFound.addAll( searchService.compassGeneSearch( csc.getSearchString() ) );
}
}
// filter genes by Taxon
Collection<Gene> genesToRemove = new ArrayList<Gene>();
if ( ( csc.getTaxon() != null ) && ( csc.getTaxon().getId() != null ) ) {
for ( Gene gene : genesFound ) {
if ( gene.getTaxon().getId().longValue() != csc.getTaxon().getId().longValue() ) {
genesToRemove.add( gene );
}
}
genesFound.removeAll( genesToRemove );
}
// if no genes found
// return error
if ( genesFound.size() == 0 ) {
saveMessage( request, "No genes found based on criteria." );
return super.showForm( request, response, errors );
}
// check if more than 1 gene found
// if yes, then query user for gene to be used
if ( genesFound.size() > 1 ) {
// check if more than 50 genes have been found.
// if there are more, then warn the user and truncate list
if ( genesFound.size() > MAX_GENES_TO_RETURN ) {
genesToRemove = new ArrayList<Gene>();
int count = 0;
for ( Gene gene : genesFound ) {
if ( count >= MAX_GENES_TO_RETURN ) {
genesToRemove.add( gene );
}
count++;
}
genesFound.removeAll( genesToRemove );
saveMessage( request, "Found " + count + " genes. Truncating list to first " + MAX_GENES_TO_RETURN
+ "." );
}
saveMessage( request, "Multiple genes matched. Choose which gene to use." );
// set to exact search
csc.setExactSearch( "on" );
ModelAndView mav = super.showForm( request, errors, getFormView() );
mav.addObject( "genes", genesFound );
return mav;
}
// At this point, only one gene has been found
// set command object to reflect this
csc.setSearchString( genesFound.iterator().next().getOfficialSymbol() );
csc.setGeneIdSearch( "false" );
// find coexpressed genes
// find expressionExperiments via lucene if the query is eestring-constrained
Collection<ExpressionExperiment> ees;
if ( StringUtils.isNotBlank( csc.getEeSearchString() ) ) {
ees = searchService.compassExpressionSearch( csc.getEeSearchString() );
if ( ees.size() == 0 ) {
saveMessage( request, "No datasets matched - defaulting to all datasets" );
}
} else {
ees = new ArrayList<ExpressionExperiment>();
}
Gene sourceGene = ( Gene ) ( genesFound.toArray() )[0];
csc.setSourceGene( sourceGene );
Integer numExpressionExperiments = 0;
Collection<Long> possibleEEs = expressionExperimentService.findByGene( sourceGene );
if ( ees.size() > 0 ) {
// if there are matches, fihter the expression experiments first by taxon
Collection<ExpressionExperiment> eeToRemove = new HashSet<ExpressionExperiment>();
for ( ExpressionExperiment ee : ees ) {
Taxon t = expressionExperimentService.getTaxon( ee.getId() );
if ( t.getId().longValue() != csc.getTaxon().getId().longValue() ) eeToRemove.add( ee );
if ( !possibleEEs.contains( ee.getId() ) ) eeToRemove.add( ee );
}
ees.removeAll( eeToRemove );
} else
ees = expressionExperimentService.load( possibleEEs );
csc.setToUseEE( ees );
numExpressionExperiments = ees.size();
// stringency. Cannot be less than 1; set to one if it is
Integer stringency = csc.getStringency();
if ( stringency == null ) {
stringency = DEFAULT_STRINGENCY;
} else if ( stringency < 1 ) {
stringency = DEFAULT_STRINGENCY;
}
csc.setStringency( stringency );
return startJob( command, request, response, errors );
}
/**
* @param request
* @return Map
*/
@SuppressWarnings("unused")
@Override
protected Map referenceData( HttpServletRequest request ) {
Map<String, List<? extends Object>> mapping = new HashMap<String, List<? extends Object>>();
// add species
populateTaxonReferenceData( mapping );
return mapping;
}
/**
* @param mapping
*/
@SuppressWarnings("unchecked")
private void populateTaxonReferenceData( Map mapping ) {
List<Taxon> taxa = new ArrayList<Taxon>();
for ( Taxon taxon : ( Collection<Taxon> ) taxonService.loadAll() ) {
if ( !SupportedTaxa.contains( taxon ) ) {
continue;
}
taxa.add( taxon );
}
Collections.sort( taxa, new Comparator<Taxon>() {
public int compare( Taxon o1, Taxon o2 ) {
return ( o1 ).getScientificName().compareTo( ( o2 ).getScientificName() );
}
} );
mapping.put( "taxa", taxa );
}
@Override
protected void initBinder( HttpServletRequest request, ServletRequestDataBinder binder ) {
super.initBinder( request, binder );
binder.registerCustomEditor( Taxon.class, new TaxonPropertyEditor( this.taxonService ) );
}
/**
* @param request
* @param csc
*/
private void loadCookie( HttpServletRequest request, CoexpressionSearchCommand csc ) {
// cookies aren't all that important, if they're missing we just go on.
if ( request == null || request.getCookies() == null ) return;
for ( Cookie cook : request.getCookies() ) {
if ( cook.getName().equals( COOKIE_NAME ) ) {
try {
ConfigurationCookie cookie = new ConfigurationCookie( cook );
csc.setEeSearchString( cookie.getString( "eeSearchString" ) );
csc.setStringency( cookie.getInt( "stringency" ) );
Taxon taxon = taxonService.findByScientificName( cookie.getString( "taxonScientificName" ) );
csc.setTaxon( taxon );
// save the gene name. If the gene id is on, then convert the ID to a gene first
String searchString = cookie.getString( "searchString" );
csc.setSearchString( searchString );
} catch ( Exception e ) {
log.warn( "Cookie could not be loaded: " + e.getMessage() );
// that's okay, we just don't get a cookie.
}
}
}
}
/**
* Fills in the command object in the case that GET parameters are passed in
*
* @param request
* @param csc
*/
private void loadGETParameters( HttpServletRequest request, CoexpressionSearchCommand csc ) {
if ( request == null || ( request.getParameter( "searchString" ) == null ) ) return;
Map params = request.getParameterMap();
if ( params.get( "eeSearchString" ) != null ) {
csc.setEeSearchString( ( ( String[] ) params.get( "eeSearchString" ) )[0] );
}
if ( params.get( "geneIdSearch" ) != null ) {
String[] geneIdSearch = ( String[] ) params.get( "geneIdSearch" );
csc.setGeneIdSearch( geneIdSearch[0] );
}
if ( params.get( "stringency" ) != null ) {
String[] stringency = ( String[] ) params.get( "stringency" );
Integer num = Integer.parseInt( stringency[0] );
csc.setStringency( num );
}
if ( params.get( "taxon" ) != null ) {
Taxon taxon = taxonService.findByScientificName( ( ( String[] ) params.get( "taxon" ) )[0] );
csc.setTaxon( taxon );
}
if ( params.get( "searchString" ) != null ) {
String searchString = ( ( String[] ) params.get( "searchString" ) )[0];
csc.setSearchString( searchString );
}
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.mvc.SimpleFormController#showForm(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, org.springframework.validation.BindException)
*/
protected ModelAndView showForm( HttpServletRequest request, HttpServletResponse response, BindException errors )
throws Exception {
if ( request.getParameter( "searchString" ) != null ) {
return this.onSubmit( request, response, this.formBackingObject( request ), errors );
}
return super.showForm( request, response, errors );
}
/**
* @param geneService
*/
public void setGeneService( GeneService geneService ) {
this.geneService = geneService;
}
/**
* @param taxonService the taxonService to set
*/
public void setTaxonService( TaxonService taxonService ) {
this.taxonService = taxonService;
}
/**
* @param searchService the searchService to set
*/
public void setSearchService( SearchService searchService ) {
this.searchService = searchService;
}
/**
* @param expressionExperimentService the expressionExperimentService to set
*/
public void setExpressionExperimentService( ExpressionExperimentService expressionExperimentService ) {
this.expressionExperimentService = expressionExperimentService;
}
@Override
protected BackgroundControllerJob<ModelAndView> getRunner( String taskId, SecurityContext securityContext,
final HttpServletRequest request, final HttpServletResponse response, final Object command,
final MessageUtil messenger, final BindException errors ) {
return new BackgroundControllerJob<ModelAndView>( taskId, securityContext, request, response, command,
messenger, errors ) {
@SuppressWarnings("unchecked")
public ModelAndView call() throws Exception {
SecurityContextHolder.setContext( securityContext );
CoexpressionSearchCommand csc = ( CoexpressionSearchCommand ) command;
ProgressJob job = ProgressManager.createProgressJob( this.getTaskId(), securityContext
.getAuthentication().getName(), "Coexpression analysis for "
+ csc.getSourceGene().getOfficialSymbol() );
job.updateProgress( "Analyzing coexpresson for " + csc.getSourceGene().getOfficialSymbol() );
CoexpressionCollectionValueObject coexpressions = ( CoexpressionCollectionValueObject ) geneService
.getCoexpressedGenes( csc.getSourceGene(), csc.getToUseEE(), csc.getStringency() );
StopWatch watch = new StopWatch();
watch.start();
// get all the coexpressed genes and sort them by dataset count
List<CoexpressionValueObject> coexpressedGenes = new ArrayList<CoexpressionValueObject>();
coexpressedGenes.addAll( coexpressions.getCoexpressionData() );
// sort coexpressed genes by dataset count
Collections.sort( coexpressedGenes, new CoexpressionComparator() );
// calculate the goOverlap for the 1st 100 genes
int i = 0;
Collection<Long> overlapIds = new HashSet<Long>();
for ( CoexpressionValueObject cvo : coexpressedGenes ) {
i++;
if ( i >= 25 ) break;
overlapIds.add( cvo.getGeneId() );
}
Map<Long,Collection<OntologyEntry>> overlap = gene2GOAssociationService.calculateGoTermOverlap( csc.getSourceGene(), overlapIds );
for ( CoexpressionValueObject cvo : coexpressedGenes ){
cvo.setGoOverlap( overlap.get( cvo.getGeneId() ) );
}
// load expression experiment value objects
Collection<Long> eeIds = new HashSet<Long>();
Collection<ExpressionExperimentValueObject> origEeVos = coexpressions.getExpressionExperiments();
for ( ExpressionExperimentValueObject eeVo : origEeVos ) {
eeIds.add( eeVo.getId() );
}
Collection<ExpressionExperimentValueObject> eeVos = expressionExperimentService
.loadValueObjects( eeIds );
// add link count information to ee value objects
// coexpressions.calculateLinkCounts();
// coexpressions.calculateRawLinkCounts();
for ( ExpressionExperimentValueObject eeVo : eeVos ) {
eeVo.setCoexpressionLinkCount( coexpressions.getLinkCountForEE( eeVo.getId() ) );
eeVo.setRawCoexpressionLinkCount( coexpressions.getRawLinkCountForEE( eeVo.getId() ) );
}
// new ModelAndView(getSuccessView());
// no genes are coexpressed
// return error
if ( coexpressedGenes.size() == 0 ) {
this.saveMessage( "No genes are coexpressed with the given stringency." );
}
Long numUsedExpressionExperiments = new Long( coexpressions.getNumberOfUsedExpressonExperiments() );
Long numPositiveCoexpressedGenes = new Long( coexpressions.getPositiveStringencyLinkCount() );
Long numNegativeCoexpressedGenes = new Long( coexpressions.getNegativeStringencyLinkCount() );
Long numGenes = new Long( coexpressions.getNumGenes() );
Long numPredictedGenes = new Long( coexpressions.getNumPredictedGenes() );
Long numProbeAlignedRegions = new Long( coexpressions.getNumProbeAlignedRegions() );
Long numStringencyGenes = new Long( coexpressions.getNumStringencyGenes() );
Long numStringencyPredictedGenes = new Long( coexpressions.getNumStringencyPredictedGenes() );
Long numStringencyProbeAlignedRegions = new Long( coexpressions.getNumStringencyProbeAlignedRegions() );
Integer numMatchedLinks = coexpressions.getLinkCount();
// addTimingInformation( request, coexpressions );
job.updateProgress( "ending...." );
ProgressManager.destroyProgressJob( job );
// request.getParameterMap().remove( "searchString" );
// request.setAttribute( "inner", "inner" );
ModelAndView mav = new ModelAndView( getSuccessView() );
// mav.setViewName( getSuccessView() );
mav.addObject( "coexpressedGenes", coexpressedGenes );
mav.addObject( "numPositiveCoexpressedGenes", numPositiveCoexpressedGenes );
mav.addObject( "numNegativeCoexpressedGenes", numNegativeCoexpressedGenes );
mav.addObject( "numSearchedExpressionExperiments", csc.getToUseEE().size() );
mav.addObject( "numUsedExpressionExperiments", numUsedExpressionExperiments );
mav.addObject( "numGenes", numGenes );
mav.addObject( "numPredictedGenes", numPredictedGenes );
mav.addObject( "numProbeAlignedRegions", numProbeAlignedRegions );
mav.addObject( "numStringencyGenes", numStringencyGenes );
mav.addObject( "numStringencyPredictedGenes", numStringencyPredictedGenes );
mav.addObject( "numStringencyProbeAlignedRegions", numStringencyProbeAlignedRegions );
mav.addObject( "numMatchedLinks", numMatchedLinks );
mav.addObject( "sourceGene", csc.getSourceGene() );
mav.addObject( "expressionExperiments", eeVos );
mav.addObject( "numLinkedExpressionExperiments", new Integer( eeVos.size() ) );
// binding objects
mav.addObject( "coexpressionSearchCommand", csc );
populateTaxonReferenceData( mav.getModel() );
mav.addAllObjects( errors.getModel() );
Long elapsed = watch.getTime();
watch.stop();
log.info( "Processing after DAO call (elapsed time): " + elapsed );
this.saveMessage( "Coexpression query took: " + coexpressions.getElapsedWallSeconds() );
return mav;
}
};
}
class CoexpressionSearchCookie extends ConfigurationCookie {
public CoexpressionSearchCookie( CoexpressionSearchCommand command ) {
super( COOKIE_NAME );
this.setProperty( "eeSearchString", command.getEeSearchString() );
// save the gene name. If the gene id is on, then convert the ID to a gene first
if ( !StringUtils.isBlank( command.getGeneIdSearch() ) ) {
String geneId = command.getSearchString();
Long id;
try {
id = Long.parseLong( geneId );
Gene g = geneService.load( id );
this.setProperty( "searchString", g.getOfficialSymbol() );
} catch ( NumberFormatException e ) {
this.setProperty( "searchString", command.getSearchString() );
}
} else {
this.setProperty( "searchString", command.getSearchString() );
}
this.setProperty( "stringency", command.getStringency() );
this.setProperty( "taxonScientificName", command.getTaxon().getScientificName() );
this.setMaxAge( 100000 );
this.setComment( "Information for coexpression search form" );
}
}
/**
* @author jsantos
*/
class CoexpressionComparator implements Comparator {
public int compare( Object o1, Object o2 ) {
CoexpressionValueObject v1 = ( ( CoexpressionValueObject ) o1 );
CoexpressionValueObject v2 = ( ( CoexpressionValueObject ) o2 );
int o1Size = v1.getExpressionExperimentValueObjects().size();
int o2Size = v2.getExpressionExperimentValueObjects().size();
if ( o1Size > o2Size ) {
return -1;
} else if ( o1Size < o2Size ) {
return 1;
} else {
return 0;
// return v2.getGeneId().compareTo( v1.getGeneId() );
}
}
}
public Gene2GOAssociationService getGene2GOAssociationService() {
return gene2GOAssociationService;
}
public void setGene2GOAssociationService( Gene2GOAssociationService gene2GOAssociationService ) {
this.gene2GOAssociationService = gene2GOAssociationService;
}
} | fixed case of no ee's to search through
| gemma-web/src/main/java/ubic/gemma/web/controller/coexpressionSearch/CoexpressionSearchController.java | fixed case of no ee's to search through | <ide><path>emma-web/src/main/java/ubic/gemma/web/controller/coexpressionSearch/CoexpressionSearchController.java
<ide> Integer numExpressionExperiments = 0;
<ide> Collection<Long> possibleEEs = expressionExperimentService.findByGene( sourceGene );
<ide>
<del> if ( ees.size() > 0 ) {
<add> if ((ees == null) || (ees.isEmpty()) ){
<add> ModelAndView mav = super.showForm( request, errors, getFormView() );
<add> saveMessage( request, "There are no " + csc.getTaxon().getScientificName() + " arrays in the system that assay for the gene " + csc.getSourceGene().getOfficialSymbol() );
<add> return mav;
<add> }
<add> else if ( ees.size() > 0 ) {
<ide> // if there are matches, fihter the expression experiments first by taxon
<ide>
<ide> Collection<ExpressionExperiment> eeToRemove = new HashSet<ExpressionExperiment>(); |
|
Java | apache-2.0 | 9e1ea524bd243f8bf2a3f593326cba5cbed4c692 | 0 | leejieyu/vtn2.0,leejieyu/vtn2.0,leejieyu/vtn2.0,leejieyu/vtn2.0 | /*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cordvtn.impl;
import com.google.common.collect.Sets;
import com.jcraft.jsch.Session;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.packet.IpAddress;
import org.onlab.util.ItemNotFoundException;
import org.onlab.util.KryoNamespace;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.LeadershipService;
import org.onosproject.cluster.NodeId;
import org.onosproject.cordvtn.api.ConnectionHandler;
import org.onosproject.cordvtn.api.CordVtnConfig;
import org.onosproject.cordvtn.api.CordVtnNode;
import org.onosproject.cordvtn.api.CordVtnNodeState;
import org.onosproject.cordvtn.api.CordVtnService;
import org.onosproject.cordvtn.api.NetworkAddress;
import org.onosproject.cordvtn.api.SshAccessInfo;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Host;
import org.onosproject.net.Port;
import org.onosproject.net.behaviour.BridgeConfig;
import org.onosproject.net.behaviour.BridgeName;
import org.onosproject.net.behaviour.ControllerInfo;
import org.onosproject.net.behaviour.DefaultTunnelDescription;
import org.onosproject.net.behaviour.TunnelConfig;
import org.onosproject.net.behaviour.TunnelDescription;
import org.onosproject.net.behaviour.TunnelName;
import org.onosproject.net.config.NetworkConfigEvent;
import org.onosproject.net.config.NetworkConfigListener;
import org.onosproject.net.config.NetworkConfigRegistry;
import org.onosproject.net.config.NetworkConfigService;
import org.onosproject.net.device.DeviceAdminService;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flow.FlowRuleService;
import org.onosproject.net.group.GroupService;
import org.onosproject.net.host.HostService;
import org.onosproject.ovsdb.controller.OvsdbClientService;
import org.onosproject.ovsdb.controller.OvsdbController;
import org.onosproject.ovsdb.controller.OvsdbNodeId;
import org.onosproject.store.serializers.KryoNamespaces;
import org.onosproject.store.service.ConsistentMap;
import org.onosproject.store.service.MapEvent;
import org.onosproject.store.service.MapEventListener;
import org.onosproject.store.service.Serializer;
import org.onosproject.store.service.StorageService;
import org.onosproject.store.service.Versioned;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.net.Device.Type.SWITCH;
import static org.onosproject.net.behaviour.TunnelDescription.Type.VXLAN;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Reads node information from the network config file and handles the config
* update events.
* Only a leader controller performs the node addition or deletion.
*/
@Component(immediate = true)
@Service(value = CordVtnNodeManager.class)
public class CordVtnNodeManager {
protected final Logger log = getLogger(getClass());
private static final KryoNamespace.Builder NODE_SERIALIZER = KryoNamespace.newBuilder()
.register(KryoNamespaces.API)
.register(CordVtnNode.class)
.register(NodeState.class)
.register(SshAccessInfo.class)
.register(NetworkAddress.class);
private static final String DEFAULT_BRIDGE = "br-int";
private static final String DEFAULT_TUNNEL = "vxlan";
private static final String VPORT_PREFIX = "tap";
private static final String OK = "OK";
private static final String NO = "NO";
private static final Map<String, String> DEFAULT_TUNNEL_OPTIONS = new HashMap<String, String>() {
{
put("key", "flow");
put("remote_ip", "flow");
}
};
private static final int DPID_BEGIN = 3;
private static final int OFPORT = 6653;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected NetworkConfigRegistry configRegistry;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected NetworkConfigService configService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected StorageService storageService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DeviceAdminService adminService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected OvsdbController controller;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected ClusterService clusterService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DeviceService deviceService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected HostService hostService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected FlowRuleService flowRuleService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected LeadershipService leadershipService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected GroupService groupService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CordVtnService cordVtnService;
private final ExecutorService eventExecutor =
newSingleThreadScheduledExecutor(groupedThreads("onos/cordvtncfg", "event-handler"));
private final NetworkConfigListener configListener = new InternalConfigListener();
private final DeviceListener deviceListener = new InternalDeviceListener();
private final MapEventListener<String, CordVtnNode> nodeStoreListener = new InternalMapListener();
private final OvsdbHandler ovsdbHandler = new OvsdbHandler();
private final BridgeHandler bridgeHandler = new BridgeHandler();
private ConsistentMap<String, CordVtnNode> nodeStore;
private CordVtnRuleInstaller ruleInstaller;
private ApplicationId appId;
private NodeId localNodeId;
private enum NodeState implements CordVtnNodeState {
INIT {
@Override
public void process(CordVtnNodeManager nodeManager, CordVtnNode node) {
if (!nodeManager.isOvsdbConnected(node)) {
nodeManager.connectOvsdb(node);
} else {
nodeManager.createIntegrationBridge(node);
}
}
},
BRIDGE_CREATED {
@Override
public void process(CordVtnNodeManager nodeManager, CordVtnNode node) {
if (!nodeManager.isOvsdbConnected(node)) {
nodeManager.connectOvsdb(node);
} else {
nodeManager.createTunnelInterface(node);
nodeManager.addDataPlaneInterface(node);
}
}
},
PORTS_ADDED {
@Override
public void process(CordVtnNodeManager nodeManager, CordVtnNode node) {
nodeManager.setIpAddress(node);
}
},
COMPLETE {
@Override
public void process(CordVtnNodeManager nodeManager, CordVtnNode node) {
nodeManager.postInit(node);
}
},
INCOMPLETE {
@Override
public void process(CordVtnNodeManager nodeManager, CordVtnNode node) {
}
};
public abstract void process(CordVtnNodeManager nodeManager, CordVtnNode node);
}
@Activate
protected void active() {
appId = coreService.getAppId(CordVtnService.CORDVTN_APP_ID);
localNodeId = clusterService.getLocalNode().id();
leadershipService.runForLeadership(appId.name());
nodeStore = storageService.<String, CordVtnNode>consistentMapBuilder()
.withSerializer(Serializer.using(NODE_SERIALIZER.build()))
.withName("cordvtn-nodestore")
.withApplicationId(appId)
.build();
ruleInstaller = new CordVtnRuleInstaller(appId, flowRuleService,
deviceService,
groupService,
configRegistry,
DEFAULT_TUNNEL);
nodeStore.addListener(nodeStoreListener);
deviceService.addListener(deviceListener);
configService.addListener(configListener);
}
@Deactivate
protected void deactivate() {
configService.removeListener(configListener);
deviceService.removeListener(deviceListener);
nodeStore.removeListener(nodeStoreListener);
nodeStore.clear();
leadershipService.withdraw(appId.name());
eventExecutor.shutdown();
}
/**
* Adds or updates a new node to the service.
*
* @param node cordvtn node
*/
public void addOrUpdateNode(CordVtnNode node) {
checkNotNull(node);
nodeStore.put(node.hostname(), CordVtnNode.getUpdatedNode(node, getNodeState(node)));
}
/**
* Deletes a node from the service.
*
* @param node cordvtn node
*/
public void deleteNode(CordVtnNode node) {
checkNotNull(node);
if (isOvsdbConnected(node)) {
disconnectOvsdb(node);
}
nodeStore.remove(node.hostname());
}
/**
* Initiates node to serve virtual tenant network.
*
* @param node cordvtn node
*/
private void initNode(CordVtnNode node) {
checkNotNull(node);
NodeState state = (NodeState) node.state();
log.debug("Processing node: {} state: {}", node.hostname(), state);
state.process(this, node);
}
/**
* Returns node initialization state.
*
* @param node cordvtn node
* @return true if initial node setup is completed, otherwise false
*/
public boolean isNodeInitComplete(CordVtnNode node) {
checkNotNull(node);
return nodeStore.containsKey(node.hostname()) && getNodeState(node).equals(NodeState.COMPLETE);
}
/**
* Flush flows installed by cordvtn.
*/
public void flushRules() {
ruleInstaller.flushRules();
}
/**
* Returns if current node state saved in nodeStore is COMPLETE or not.
*
* @param node cordvtn node
* @return true if it's complete state, otherwise false
*/
private boolean isNodeStateComplete(CordVtnNode node) {
checkNotNull(node);
// the state saved in nodeStore can be wrong if IP address settings are changed
// after the node init has been completed since there's no way to detect it
// getNodeState and checkNodeInitState always return correct answer but can be slow
Versioned<CordVtnNode> versionedNode = nodeStore.get(node.hostname());
CordVtnNodeState state = versionedNode.value().state();
return state != null && state.equals(NodeState.COMPLETE);
}
/**
* Returns detailed node initialization state.
*
* @param node cordvtn node
* @return string including detailed node init state
*/
public String checkNodeInitState(CordVtnNode node) {
checkNotNull(node);
if (!nodeStore.containsKey(node.hostname())) {
log.warn("Node {} does not exist, add node first", node.hostname());
return null;
}
Session session = RemoteIpCommandUtil.connect(node.sshInfo());
if (session == null) {
log.debug("Failed to SSH to {}", node.hostname());
return null;
}
Set<IpAddress> intBrIps = RemoteIpCommandUtil.getCurrentIps(session, DEFAULT_BRIDGE);
String result = String.format(
"br-int created and connected : %s (%s)%n" +
"VXLAN interface created : %s%n" +
"Data plane interface added : %s (%s)%n" +
"IP flushed from %s : %s%n" +
"Data plane IP added to br-int : %s (%s)%n" +
"Local management IP added to br-int : %s (%s)",
isBrIntCreated(node) ? OK : NO, node.intBrId(),
isTunnelIntfCreated(node) ? OK : NO,
isDataPlaneIntfAdded(node) ? OK : NO, node.dpIntf(),
node.dpIntf(),
RemoteIpCommandUtil.getCurrentIps(session, node.dpIntf()).isEmpty() ? OK : NO,
intBrIps.contains(node.dpIp().ip()) ? OK : NO, node.dpIp().cidr(),
intBrIps.contains(node.localMgmtIp().ip()) ? OK : NO, node.localMgmtIp().cidr());
RemoteIpCommandUtil.disconnect(session);
return result;
}
/**
* Returns the number of the nodes known to the service.
*
* @return number of nodes
*/
public int getNodeCount() {
return nodeStore.size();
}
/**
* Returns all nodes known to the service.
*
* @return list of nodes
*/
public List<CordVtnNode> getNodes() {
return nodeStore.values().stream()
.map(Versioned::value)
.collect(Collectors.toList());
}
/**
* Returns cordvtn node associated with a given OVSDB device.
*
* @param ovsdbId OVSDB device id
* @return cordvtn node, null if it fails to find the node
*/
private CordVtnNode getNodeByOvsdbId(DeviceId ovsdbId) {
return getNodes().stream()
.filter(node -> node.ovsdbId().equals(ovsdbId))
.findFirst().orElse(null);
}
/**
* Returns cordvtn node associated with a given integration bridge.
*
* @param bridgeId device id of integration bridge
* @return cordvtn node, null if it fails to find the node
*/
private CordVtnNode getNodeByBridgeId(DeviceId bridgeId) {
return getNodes().stream()
.filter(node -> node.intBrId().equals(bridgeId))
.findFirst().orElse(null);
}
/**
* Sets a new state for a given cordvtn node.
*
* @param node cordvtn node
* @param newState new node state
*/
private void setNodeState(CordVtnNode node, NodeState newState) {
checkNotNull(node);
log.debug("Changed {} state: {}", node.hostname(), newState);
nodeStore.put(node.hostname(), CordVtnNode.getUpdatedNode(node, newState));
}
/**
* Checks current state of a given cordvtn node and returns it.
*
* @param node cordvtn node
* @return node state
*/
private NodeState getNodeState(CordVtnNode node) {
checkNotNull(node);
if (isBrIntCreated(node) && isTunnelIntfCreated(node) &&
isDataPlaneIntfAdded(node) && isIpAddressSet(node)) {
return NodeState.COMPLETE;
} else if (isDataPlaneIntfAdded(node) && isTunnelIntfCreated(node)) {
return NodeState.PORTS_ADDED;
} else if (isBrIntCreated(node)) {
return NodeState.BRIDGE_CREATED;
} else {
return NodeState.INIT;
}
}
/**
* Performs tasks after node initialization.
* It disconnects unnecessary OVSDB connection and installs initial flow
* rules on the device.
*
* @param node cordvtn node
*/
private void postInit(CordVtnNode node) {
disconnectOvsdb(node);
ruleInstaller.init(node.intBrId(), node.dpIntf(), node.dpIp().ip());
// add existing hosts to the service
deviceService.getPorts(node.intBrId()).stream()
.filter(port -> getPortName(port).startsWith(VPORT_PREFIX) &&
port.isEnabled())
.forEach(port -> cordVtnService.addServiceVm(node, getConnectPoint(port)));
// remove stale hosts from the service
hostService.getHosts().forEach(host -> {
Port port = deviceService.getPort(host.location().deviceId(), host.location().port());
if (port == null) {
cordVtnService.removeServiceVm(getConnectPoint(host));
}
});
log.info("Finished init {}", node.hostname());
}
/**
* Returns port name.
*
* @param port port
* @return port name
*/
private String getPortName(Port port) {
return port.annotations().value("portName");
}
/**
* Returns connection state of OVSDB server for a given node.
*
* @param node cordvtn node
* @return true if it is connected, false otherwise
*/
private boolean isOvsdbConnected(CordVtnNode node) {
checkNotNull(node);
OvsdbClientService ovsdbClient = getOvsdbClient(node);
return deviceService.isAvailable(node.ovsdbId()) &&
ovsdbClient != null && ovsdbClient.isConnected();
}
/**
* Connects to OVSDB server for a given node.
*
* @param node cordvtn node
*/
private void connectOvsdb(CordVtnNode node) {
checkNotNull(node);
if (!nodeStore.containsKey(node.hostname())) {
log.warn("Node {} does not exist", node.hostname());
return;
}
if (!isOvsdbConnected(node)) {
controller.connect(node.hostMgmtIp().ip(), node.ovsdbPort());
}
}
/**
* Disconnects OVSDB server for a given node.
*
* @param node cordvtn node
*/
private void disconnectOvsdb(CordVtnNode node) {
checkNotNull(node);
if (!nodeStore.containsKey(node.hostname())) {
log.warn("Node {} does not exist", node.hostname());
return;
}
if (isOvsdbConnected(node)) {
OvsdbClientService ovsdbClient = getOvsdbClient(node);
ovsdbClient.disconnect();
}
}
/**
* Returns OVSDB client for a given node.
*
* @param node cordvtn node
* @return OVSDB client, or null if it fails to get OVSDB client
*/
private OvsdbClientService getOvsdbClient(CordVtnNode node) {
checkNotNull(node);
OvsdbClientService ovsdbClient = controller.getOvsdbClient(
new OvsdbNodeId(node.hostMgmtIp().ip(), node.ovsdbPort().toInt()));
if (ovsdbClient == null) {
log.trace("Couldn't find OVSDB client for {}", node.hostname());
}
return ovsdbClient;
}
/**
* Creates an integration bridge for a given node.
*
* @param node cordvtn node
*/
private void createIntegrationBridge(CordVtnNode node) {
if (isBrIntCreated(node)) {
return;
}
List<ControllerInfo> controllers = new ArrayList<>();
Sets.newHashSet(clusterService.getNodes()).stream()
.forEach(controller -> {
ControllerInfo ctrlInfo = new ControllerInfo(controller.ip(), OFPORT, "tcp");
controllers.add(ctrlInfo);
});
String dpid = node.intBrId().toString().substring(DPID_BEGIN);
try {
Device device = deviceService.getDevice(node.ovsdbId());
if (device.is(BridgeConfig.class)) {
BridgeConfig bridgeConfig = device.as(BridgeConfig.class);
bridgeConfig.addBridge(BridgeName.bridgeName(DEFAULT_BRIDGE), dpid, controllers);
} else {
log.warn("The bridging behaviour is not supported in device {}", device.id().toString());
}
} catch (ItemNotFoundException e) {
log.warn("Failed to create integration bridge on {}", node.hostname());
}
}
/**
* Creates tunnel interface to the integration bridge for a given node.
*
* @param node cordvtn node
*/
private void createTunnelInterface(CordVtnNode node) {
if (isTunnelIntfCreated(node)) {
return;
}
DefaultAnnotations.Builder optionBuilder = DefaultAnnotations.builder();
for (String key : DEFAULT_TUNNEL_OPTIONS.keySet()) {
optionBuilder.set(key, DEFAULT_TUNNEL_OPTIONS.get(key));
}
TunnelDescription description = new DefaultTunnelDescription(
null, null, VXLAN, TunnelName.tunnelName(DEFAULT_TUNNEL),
optionBuilder.build());
try {
Device device = deviceService.getDevice(node.ovsdbId());
if (device.is(TunnelConfig.class)) {
TunnelConfig tunnelConfig = device.as(TunnelConfig.class);
tunnelConfig.createTunnelInterface(BridgeName.bridgeName(DEFAULT_BRIDGE), description);
} else {
log.warn("The tunneling behaviour is not supported in device {}", device.id().toString());
}
} catch (ItemNotFoundException e) {
log.warn("Failed to create tunnel interface on {}", node.hostname());
}
}
/**
* Adds data plane interface to a given node.
*
* @param node cordvtn node
*/
private void addDataPlaneInterface(CordVtnNode node) {
if (isDataPlaneIntfAdded(node)) {
return;
}
try {
Device device = deviceService.getDevice(node.ovsdbId());
if (device.is(BridgeConfig.class)) {
BridgeConfig bridgeConfig = device.as(BridgeConfig.class);
bridgeConfig.addPort(BridgeName.bridgeName(DEFAULT_BRIDGE), node.dpIntf());
} else {
log.warn("The bridging behaviour is not supported in device {}", device.id().toString());
}
} catch (ItemNotFoundException e) {
log.warn("Failed to add {} on {}", node.dpIntf(), node.hostname());
}
}
/**
* Flushes IP address from data plane interface and adds data plane IP address
* to integration bridge.
*
* @param node cordvtn node
*/
private void setIpAddress(CordVtnNode node) {
Session session = RemoteIpCommandUtil.connect(node.sshInfo());
if (session == null) {
log.debug("Failed to SSH to {}", node.hostname());
return;
}
RemoteIpCommandUtil.getCurrentIps(session, DEFAULT_BRIDGE).stream()
.filter(ip -> !ip.equals(node.localMgmtIp().ip()))
.filter(ip -> !ip.equals(node.dpIp().ip()))
.forEach(ip -> RemoteIpCommandUtil.deleteIp(session, ip, DEFAULT_BRIDGE));
boolean result = RemoteIpCommandUtil.flushIp(session, node.dpIntf()) &&
RemoteIpCommandUtil.setInterfaceUp(session, node.dpIntf()) &&
RemoteIpCommandUtil.addIp(session, node.dpIp(), DEFAULT_BRIDGE) &&
RemoteIpCommandUtil.addIp(session, node.localMgmtIp(), DEFAULT_BRIDGE) &&
RemoteIpCommandUtil.setInterfaceUp(session, DEFAULT_BRIDGE);
RemoteIpCommandUtil.disconnect(session);
if (result) {
setNodeState(node, NodeState.COMPLETE);
}
}
/**
* Checks if integration bridge exists and available.
*
* @param node cordvtn node
* @return true if the bridge is available, false otherwise
*/
private boolean isBrIntCreated(CordVtnNode node) {
return (deviceService.getDevice(node.intBrId()) != null
&& deviceService.isAvailable(node.intBrId()));
}
/**
* Checks if tunnel interface exists.
*
* @param node cordvtn node
* @return true if the interface exists, false otherwise
*/
private boolean isTunnelIntfCreated(CordVtnNode node) {
return deviceService.getPorts(node.intBrId())
.stream()
.filter(p -> getPortName(p).contains(DEFAULT_TUNNEL) &&
p.isEnabled())
.findAny().isPresent();
}
/**
* Checks if data plane interface exists.
*
* @param node cordvtn node
* @return true if the interface exists, false otherwise
*/
private boolean isDataPlaneIntfAdded(CordVtnNode node) {
return deviceService.getPorts(node.intBrId())
.stream()
.filter(p -> getPortName(p).contains(node.dpIntf()) &&
p.isEnabled())
.findAny().isPresent();
}
/**
* Checks if the IP addresses are correctly set.
*
* @param node cordvtn node
* @return true if the IP is set, false otherwise
*/
private boolean isIpAddressSet(CordVtnNode node) {
Session session = RemoteIpCommandUtil.connect(node.sshInfo());
if (session == null) {
log.debug("Failed to SSH to {}", node.hostname());
return false;
}
Set<IpAddress> intBrIps = RemoteIpCommandUtil.getCurrentIps(session, DEFAULT_BRIDGE);
boolean result = RemoteIpCommandUtil.getCurrentIps(session, node.dpIntf()).isEmpty() &&
RemoteIpCommandUtil.isInterfaceUp(session, node.dpIntf()) &&
intBrIps.contains(node.dpIp().ip()) &&
intBrIps.contains(node.localMgmtIp().ip()) &&
RemoteIpCommandUtil.isInterfaceUp(session, DEFAULT_BRIDGE);
RemoteIpCommandUtil.disconnect(session);
return result;
}
/**
* Returns connect point of a given port.
*
* @param port port
* @return connect point
*/
private ConnectPoint getConnectPoint(Port port) {
return new ConnectPoint(port.element().id(), port.number());
}
/**
* Returns connect point of a given host.
*
* @param host host
* @return connect point
*/
private ConnectPoint getConnectPoint(Host host) {
return new ConnectPoint(host.location().deviceId(), host.location().port());
}
private class OvsdbHandler implements ConnectionHandler<Device> {
@Override
public void connected(Device device) {
CordVtnNode node = getNodeByOvsdbId(device.id());
if (node != null) {
setNodeState(node, getNodeState(node));
} else {
log.debug("{} is detected on unregistered node, ignore it.", device.id());
}
}
@Override
public void disconnected(Device device) {
if (!deviceService.isAvailable(device.id())) {
log.debug("Device {} is disconnected", device.id());
adminService.removeDevice(device.id());
}
}
}
private class BridgeHandler implements ConnectionHandler<Device> {
@Override
public void connected(Device device) {
CordVtnNode node = getNodeByBridgeId(device.id());
if (node != null) {
setNodeState(node, getNodeState(node));
} else {
log.debug("{} is detected on unregistered node, ignore it.", device.id());
}
}
@Override
public void disconnected(Device device) {
CordVtnNode node = getNodeByBridgeId(device.id());
if (node != null) {
log.debug("Integration Bridge is disconnected from {}", node.hostname());
setNodeState(node, NodeState.INCOMPLETE);
}
}
/**
* Handles port added situation.
* If the added port is tunnel or data plane interface, proceed to the remaining
* node initialization. Otherwise, do nothing.
*
* @param port port
*/
public void portAdded(Port port) {
CordVtnNode node = getNodeByBridgeId((DeviceId) port.element().id());
String portName = getPortName(port);
if (node == null) {
log.debug("{} is added to unregistered node, ignore it.", portName);
return;
}
log.info("Port {} is added to {}", portName, node.hostname());
if (portName.startsWith(VPORT_PREFIX)) {
if (isNodeStateComplete(node)) {
cordVtnService.addServiceVm(node, getConnectPoint(port));
} else {
log.debug("VM is detected on incomplete node, ignore it.", portName);
}
} else if (portName.contains(DEFAULT_TUNNEL) || portName.equals(node.dpIntf())) {
setNodeState(node, getNodeState(node));
}
}
/**
* Handles port removed situation.
* If the removed port is tunnel or data plane interface, proceed to the remaining
* node initialization.Others, do nothing.
*
* @param port port
*/
public void portRemoved(Port port) {
CordVtnNode node = getNodeByBridgeId((DeviceId) port.element().id());
String portName = getPortName(port);
if (node == null) {
return;
}
log.info("Port {} is removed from {}", portName, node.hostname());
if (portName.startsWith(VPORT_PREFIX)) {
if (isNodeStateComplete(node)) {
cordVtnService.removeServiceVm(getConnectPoint(port));
} else {
log.debug("VM is vanished from incomplete node, ignore it.", portName);
}
} else if (portName.contains(DEFAULT_TUNNEL) || portName.equals(node.dpIntf())) {
setNodeState(node, NodeState.INCOMPLETE);
}
}
}
private class InternalDeviceListener implements DeviceListener {
@Override
public void event(DeviceEvent event) {
NodeId leaderNodeId = leadershipService.getLeader(appId.name());
if (!Objects.equals(localNodeId, leaderNodeId)) {
// do not allow to proceed without leadership
return;
}
Device device = event.subject();
ConnectionHandler<Device> handler =
(device.type().equals(SWITCH) ? bridgeHandler : ovsdbHandler);
switch (event.type()) {
case PORT_ADDED:
eventExecutor.execute(() -> bridgeHandler.portAdded(event.port()));
break;
case PORT_UPDATED:
if (!event.port().isEnabled()) {
eventExecutor.execute(() -> bridgeHandler.portRemoved(event.port()));
}
break;
case DEVICE_ADDED:
case DEVICE_AVAILABILITY_CHANGED:
if (deviceService.isAvailable(device.id())) {
eventExecutor.execute(() -> handler.connected(device));
} else {
eventExecutor.execute(() -> handler.disconnected(device));
}
break;
default:
break;
}
}
}
/**
* Reads cordvtn nodes from config file.
*/
private void readConfiguration() {
CordVtnConfig config = configRegistry.getConfig(appId, CordVtnConfig.class);
if (config == null) {
log.debug("No configuration found");
return;
}
config.cordVtnNodes().forEach(this::addOrUpdateNode);
}
private class InternalConfigListener implements NetworkConfigListener {
@Override
public void event(NetworkConfigEvent event) {
NodeId leaderNodeId = leadershipService.getLeader(appId.name());
if (!Objects.equals(localNodeId, leaderNodeId)) {
// do not allow to proceed without leadership
return;
}
if (!event.configClass().equals(CordVtnConfig.class)) {
return;
}
switch (event.type()) {
case CONFIG_ADDED:
case CONFIG_UPDATED:
eventExecutor.execute(CordVtnNodeManager.this::readConfiguration);
break;
default:
break;
}
}
}
private class InternalMapListener implements MapEventListener<String, CordVtnNode> {
@Override
public void event(MapEvent<String, CordVtnNode> event) {
NodeId leaderNodeId = leadershipService.getLeader(appId.name());
if (!Objects.equals(localNodeId, leaderNodeId)) {
// do not allow to proceed without leadership
return;
}
CordVtnNode oldNode;
CordVtnNode newNode;
switch (event.type()) {
case UPDATE:
oldNode = event.oldValue().value();
newNode = event.newValue().value();
if (!newNode.equals(oldNode)) {
log.info("{} has been updated", newNode.hostname());
log.debug("New node: {}", newNode);
}
// perform init procedure based on current state on any updates,
// insert, or even if the node is the same for robustness since
// it's no harm to run the init procedure multiple times
eventExecutor.execute(() -> initNode(newNode));
break;
case INSERT:
newNode = event.newValue().value();
log.info("Added {}", newNode.hostname());
eventExecutor.execute(() -> initNode(newNode));
break;
case REMOVE:
oldNode = event.oldValue().value();
log.info("{} is removed", oldNode.hostname());
break;
default:
break;
}
}
}
}
| src/main/java/org/onosproject/cordvtn/impl/CordVtnNodeManager.java | /*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cordvtn.impl;
import com.google.common.collect.Sets;
import com.jcraft.jsch.Session;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.packet.IpAddress;
import org.onlab.util.ItemNotFoundException;
import org.onlab.util.KryoNamespace;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.LeadershipService;
import org.onosproject.cluster.NodeId;
import org.onosproject.cordvtn.api.ConnectionHandler;
import org.onosproject.cordvtn.api.CordVtnConfig;
import org.onosproject.cordvtn.api.CordVtnNode;
import org.onosproject.cordvtn.api.CordVtnNodeState;
import org.onosproject.cordvtn.api.CordVtnService;
import org.onosproject.cordvtn.api.NetworkAddress;
import org.onosproject.cordvtn.api.SshAccessInfo;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Host;
import org.onosproject.net.Port;
import org.onosproject.net.behaviour.BridgeConfig;
import org.onosproject.net.behaviour.BridgeName;
import org.onosproject.net.behaviour.ControllerInfo;
import org.onosproject.net.behaviour.DefaultTunnelDescription;
import org.onosproject.net.behaviour.TunnelConfig;
import org.onosproject.net.behaviour.TunnelDescription;
import org.onosproject.net.behaviour.TunnelName;
import org.onosproject.net.config.NetworkConfigEvent;
import org.onosproject.net.config.NetworkConfigListener;
import org.onosproject.net.config.NetworkConfigRegistry;
import org.onosproject.net.config.NetworkConfigService;
import org.onosproject.net.device.DeviceAdminService;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flow.FlowRuleService;
import org.onosproject.net.group.GroupService;
import org.onosproject.net.host.HostService;
import org.onosproject.ovsdb.controller.OvsdbClientService;
import org.onosproject.ovsdb.controller.OvsdbController;
import org.onosproject.ovsdb.controller.OvsdbNodeId;
import org.onosproject.store.serializers.KryoNamespaces;
import org.onosproject.store.service.ConsistentMap;
import org.onosproject.store.service.MapEvent;
import org.onosproject.store.service.MapEventListener;
import org.onosproject.store.service.Serializer;
import org.onosproject.store.service.StorageService;
import org.onosproject.store.service.Versioned;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.net.Device.Type.SWITCH;
import static org.onosproject.net.behaviour.TunnelDescription.Type.VXLAN;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Reads node information from the network config file and handles the config
* update events.
* Only a leader controller performs the node addition or deletion.
*/
@Component(immediate = true)
@Service(value = CordVtnNodeManager.class)
public class CordVtnNodeManager {
protected final Logger log = getLogger(getClass());
private static final KryoNamespace.Builder NODE_SERIALIZER = KryoNamespace.newBuilder()
.register(KryoNamespaces.API)
.register(KryoNamespaces.MISC)
.register(CordVtnNode.class)
.register(NodeState.class)
.register(SshAccessInfo.class)
.register(NetworkAddress.class);
private static final String DEFAULT_BRIDGE = "br-int";
private static final String DEFAULT_TUNNEL = "vxlan";
private static final String VPORT_PREFIX = "tap";
private static final String OK = "OK";
private static final String NO = "NO";
private static final Map<String, String> DEFAULT_TUNNEL_OPTIONS = new HashMap<String, String>() {
{
put("key", "flow");
put("remote_ip", "flow");
}
};
private static final int DPID_BEGIN = 3;
private static final int OFPORT = 6653;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected NetworkConfigRegistry configRegistry;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected NetworkConfigService configService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected StorageService storageService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DeviceAdminService adminService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected OvsdbController controller;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected ClusterService clusterService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DeviceService deviceService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected HostService hostService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected FlowRuleService flowRuleService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected LeadershipService leadershipService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected GroupService groupService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CordVtnService cordVtnService;
private final ExecutorService eventExecutor =
newSingleThreadScheduledExecutor(groupedThreads("onos/cordvtncfg", "event-handler"));
private final NetworkConfigListener configListener = new InternalConfigListener();
private final DeviceListener deviceListener = new InternalDeviceListener();
private final MapEventListener<String, CordVtnNode> nodeStoreListener = new InternalMapListener();
private final OvsdbHandler ovsdbHandler = new OvsdbHandler();
private final BridgeHandler bridgeHandler = new BridgeHandler();
private ConsistentMap<String, CordVtnNode> nodeStore;
private CordVtnRuleInstaller ruleInstaller;
private ApplicationId appId;
private NodeId localNodeId;
private enum NodeState implements CordVtnNodeState {
INIT {
@Override
public void process(CordVtnNodeManager nodeManager, CordVtnNode node) {
if (!nodeManager.isOvsdbConnected(node)) {
nodeManager.connectOvsdb(node);
} else {
nodeManager.createIntegrationBridge(node);
}
}
},
BRIDGE_CREATED {
@Override
public void process(CordVtnNodeManager nodeManager, CordVtnNode node) {
if (!nodeManager.isOvsdbConnected(node)) {
nodeManager.connectOvsdb(node);
} else {
nodeManager.createTunnelInterface(node);
nodeManager.addDataPlaneInterface(node);
}
}
},
PORTS_ADDED {
@Override
public void process(CordVtnNodeManager nodeManager, CordVtnNode node) {
nodeManager.setIpAddress(node);
}
},
COMPLETE {
@Override
public void process(CordVtnNodeManager nodeManager, CordVtnNode node) {
nodeManager.postInit(node);
}
},
INCOMPLETE {
@Override
public void process(CordVtnNodeManager nodeManager, CordVtnNode node) {
}
};
public abstract void process(CordVtnNodeManager nodeManager, CordVtnNode node);
}
@Activate
protected void active() {
appId = coreService.getAppId(CordVtnService.CORDVTN_APP_ID);
localNodeId = clusterService.getLocalNode().id();
leadershipService.runForLeadership(appId.name());
nodeStore = storageService.<String, CordVtnNode>consistentMapBuilder()
.withSerializer(Serializer.using(NODE_SERIALIZER.build()))
.withName("cordvtn-nodestore")
.withApplicationId(appId)
.build();
ruleInstaller = new CordVtnRuleInstaller(appId, flowRuleService,
deviceService,
groupService,
configRegistry,
DEFAULT_TUNNEL);
nodeStore.addListener(nodeStoreListener);
deviceService.addListener(deviceListener);
configService.addListener(configListener);
}
@Deactivate
protected void deactivate() {
configService.removeListener(configListener);
deviceService.removeListener(deviceListener);
nodeStore.removeListener(nodeStoreListener);
nodeStore.clear();
leadershipService.withdraw(appId.name());
eventExecutor.shutdown();
}
/**
* Adds or updates a new node to the service.
*
* @param node cordvtn node
*/
public void addOrUpdateNode(CordVtnNode node) {
checkNotNull(node);
nodeStore.put(node.hostname(), CordVtnNode.getUpdatedNode(node, getNodeState(node)));
}
/**
* Deletes a node from the service.
*
* @param node cordvtn node
*/
public void deleteNode(CordVtnNode node) {
checkNotNull(node);
if (isOvsdbConnected(node)) {
disconnectOvsdb(node);
}
nodeStore.remove(node.hostname());
}
/**
* Initiates node to serve virtual tenant network.
*
* @param node cordvtn node
*/
private void initNode(CordVtnNode node) {
checkNotNull(node);
NodeState state = (NodeState) node.state();
log.debug("Processing node: {} state: {}", node.hostname(), state);
state.process(this, node);
}
/**
* Returns node initialization state.
*
* @param node cordvtn node
* @return true if initial node setup is completed, otherwise false
*/
public boolean isNodeInitComplete(CordVtnNode node) {
checkNotNull(node);
return nodeStore.containsKey(node.hostname()) && getNodeState(node).equals(NodeState.COMPLETE);
}
/**
* Flush flows installed by cordvtn.
*/
public void flushRules() {
ruleInstaller.flushRules();
}
/**
* Returns if current node state saved in nodeStore is COMPLETE or not.
*
* @param node cordvtn node
* @return true if it's complete state, otherwise false
*/
private boolean isNodeStateComplete(CordVtnNode node) {
checkNotNull(node);
// the state saved in nodeStore can be wrong if IP address settings are changed
// after the node init has been completed since there's no way to detect it
// getNodeState and checkNodeInitState always return correct answer but can be slow
Versioned<CordVtnNode> versionedNode = nodeStore.get(node.hostname());
CordVtnNodeState state = versionedNode.value().state();
return state != null && state.equals(NodeState.COMPLETE);
}
/**
* Returns detailed node initialization state.
*
* @param node cordvtn node
* @return string including detailed node init state
*/
public String checkNodeInitState(CordVtnNode node) {
checkNotNull(node);
if (!nodeStore.containsKey(node.hostname())) {
log.warn("Node {} does not exist, add node first", node.hostname());
return null;
}
Session session = RemoteIpCommandUtil.connect(node.sshInfo());
if (session == null) {
log.debug("Failed to SSH to {}", node.hostname());
return null;
}
Set<IpAddress> intBrIps = RemoteIpCommandUtil.getCurrentIps(session, DEFAULT_BRIDGE);
String result = String.format(
"br-int created and connected : %s (%s)%n" +
"VXLAN interface created : %s%n" +
"Data plane interface added : %s (%s)%n" +
"IP flushed from %s : %s%n" +
"Data plane IP added to br-int : %s (%s)%n" +
"Local management IP added to br-int : %s (%s)",
isBrIntCreated(node) ? OK : NO, node.intBrId(),
isTunnelIntfCreated(node) ? OK : NO,
isDataPlaneIntfAdded(node) ? OK : NO, node.dpIntf(),
node.dpIntf(),
RemoteIpCommandUtil.getCurrentIps(session, node.dpIntf()).isEmpty() ? OK : NO,
intBrIps.contains(node.dpIp().ip()) ? OK : NO, node.dpIp().cidr(),
intBrIps.contains(node.localMgmtIp().ip()) ? OK : NO, node.localMgmtIp().cidr());
RemoteIpCommandUtil.disconnect(session);
return result;
}
/**
* Returns the number of the nodes known to the service.
*
* @return number of nodes
*/
public int getNodeCount() {
return nodeStore.size();
}
/**
* Returns all nodes known to the service.
*
* @return list of nodes
*/
public List<CordVtnNode> getNodes() {
return nodeStore.values().stream()
.map(Versioned::value)
.collect(Collectors.toList());
}
/**
* Returns cordvtn node associated with a given OVSDB device.
*
* @param ovsdbId OVSDB device id
* @return cordvtn node, null if it fails to find the node
*/
private CordVtnNode getNodeByOvsdbId(DeviceId ovsdbId) {
return getNodes().stream()
.filter(node -> node.ovsdbId().equals(ovsdbId))
.findFirst().orElse(null);
}
/**
* Returns cordvtn node associated with a given integration bridge.
*
* @param bridgeId device id of integration bridge
* @return cordvtn node, null if it fails to find the node
*/
private CordVtnNode getNodeByBridgeId(DeviceId bridgeId) {
return getNodes().stream()
.filter(node -> node.intBrId().equals(bridgeId))
.findFirst().orElse(null);
}
/**
* Sets a new state for a given cordvtn node.
*
* @param node cordvtn node
* @param newState new node state
*/
private void setNodeState(CordVtnNode node, NodeState newState) {
checkNotNull(node);
log.debug("Changed {} state: {}", node.hostname(), newState);
nodeStore.put(node.hostname(), CordVtnNode.getUpdatedNode(node, newState));
}
/**
* Checks current state of a given cordvtn node and returns it.
*
* @param node cordvtn node
* @return node state
*/
private NodeState getNodeState(CordVtnNode node) {
checkNotNull(node);
if (isBrIntCreated(node) && isTunnelIntfCreated(node) &&
isDataPlaneIntfAdded(node) && isIpAddressSet(node)) {
return NodeState.COMPLETE;
} else if (isDataPlaneIntfAdded(node) && isTunnelIntfCreated(node)) {
return NodeState.PORTS_ADDED;
} else if (isBrIntCreated(node)) {
return NodeState.BRIDGE_CREATED;
} else {
return NodeState.INIT;
}
}
/**
* Performs tasks after node initialization.
* It disconnects unnecessary OVSDB connection and installs initial flow
* rules on the device.
*
* @param node cordvtn node
*/
private void postInit(CordVtnNode node) {
disconnectOvsdb(node);
ruleInstaller.init(node.intBrId(), node.dpIntf(), node.dpIp().ip());
// add existing hosts to the service
deviceService.getPorts(node.intBrId()).stream()
.filter(port -> getPortName(port).startsWith(VPORT_PREFIX) &&
port.isEnabled())
.forEach(port -> cordVtnService.addServiceVm(node, getConnectPoint(port)));
// remove stale hosts from the service
hostService.getHosts().forEach(host -> {
Port port = deviceService.getPort(host.location().deviceId(), host.location().port());
if (port == null) {
cordVtnService.removeServiceVm(getConnectPoint(host));
}
});
log.info("Finished init {}", node.hostname());
}
/**
* Returns port name.
*
* @param port port
* @return port name
*/
private String getPortName(Port port) {
return port.annotations().value("portName");
}
/**
* Returns connection state of OVSDB server for a given node.
*
* @param node cordvtn node
* @return true if it is connected, false otherwise
*/
private boolean isOvsdbConnected(CordVtnNode node) {
checkNotNull(node);
OvsdbClientService ovsdbClient = getOvsdbClient(node);
return deviceService.isAvailable(node.ovsdbId()) &&
ovsdbClient != null && ovsdbClient.isConnected();
}
/**
* Connects to OVSDB server for a given node.
*
* @param node cordvtn node
*/
private void connectOvsdb(CordVtnNode node) {
checkNotNull(node);
if (!nodeStore.containsKey(node.hostname())) {
log.warn("Node {} does not exist", node.hostname());
return;
}
if (!isOvsdbConnected(node)) {
controller.connect(node.hostMgmtIp().ip(), node.ovsdbPort());
}
}
/**
* Disconnects OVSDB server for a given node.
*
* @param node cordvtn node
*/
private void disconnectOvsdb(CordVtnNode node) {
checkNotNull(node);
if (!nodeStore.containsKey(node.hostname())) {
log.warn("Node {} does not exist", node.hostname());
return;
}
if (isOvsdbConnected(node)) {
OvsdbClientService ovsdbClient = getOvsdbClient(node);
ovsdbClient.disconnect();
}
}
/**
* Returns OVSDB client for a given node.
*
* @param node cordvtn node
* @return OVSDB client, or null if it fails to get OVSDB client
*/
private OvsdbClientService getOvsdbClient(CordVtnNode node) {
checkNotNull(node);
OvsdbClientService ovsdbClient = controller.getOvsdbClient(
new OvsdbNodeId(node.hostMgmtIp().ip(), node.ovsdbPort().toInt()));
if (ovsdbClient == null) {
log.trace("Couldn't find OVSDB client for {}", node.hostname());
}
return ovsdbClient;
}
/**
* Creates an integration bridge for a given node.
*
* @param node cordvtn node
*/
private void createIntegrationBridge(CordVtnNode node) {
if (isBrIntCreated(node)) {
return;
}
List<ControllerInfo> controllers = new ArrayList<>();
Sets.newHashSet(clusterService.getNodes()).stream()
.forEach(controller -> {
ControllerInfo ctrlInfo = new ControllerInfo(controller.ip(), OFPORT, "tcp");
controllers.add(ctrlInfo);
});
String dpid = node.intBrId().toString().substring(DPID_BEGIN);
try {
Device device = deviceService.getDevice(node.ovsdbId());
if (device.is(BridgeConfig.class)) {
BridgeConfig bridgeConfig = device.as(BridgeConfig.class);
bridgeConfig.addBridge(BridgeName.bridgeName(DEFAULT_BRIDGE), dpid, controllers);
} else {
log.warn("The bridging behaviour is not supported in device {}", device.id().toString());
}
} catch (ItemNotFoundException e) {
log.warn("Failed to create integration bridge on {}", node.hostname());
}
}
/**
* Creates tunnel interface to the integration bridge for a given node.
*
* @param node cordvtn node
*/
private void createTunnelInterface(CordVtnNode node) {
if (isTunnelIntfCreated(node)) {
return;
}
DefaultAnnotations.Builder optionBuilder = DefaultAnnotations.builder();
for (String key : DEFAULT_TUNNEL_OPTIONS.keySet()) {
optionBuilder.set(key, DEFAULT_TUNNEL_OPTIONS.get(key));
}
TunnelDescription description = new DefaultTunnelDescription(
null, null, VXLAN, TunnelName.tunnelName(DEFAULT_TUNNEL),
optionBuilder.build());
try {
Device device = deviceService.getDevice(node.ovsdbId());
if (device.is(TunnelConfig.class)) {
TunnelConfig tunnelConfig = device.as(TunnelConfig.class);
tunnelConfig.createTunnelInterface(BridgeName.bridgeName(DEFAULT_BRIDGE), description);
} else {
log.warn("The tunneling behaviour is not supported in device {}", device.id().toString());
}
} catch (ItemNotFoundException e) {
log.warn("Failed to create tunnel interface on {}", node.hostname());
}
}
/**
* Adds data plane interface to a given node.
*
* @param node cordvtn node
*/
private void addDataPlaneInterface(CordVtnNode node) {
if (isDataPlaneIntfAdded(node)) {
return;
}
try {
Device device = deviceService.getDevice(node.ovsdbId());
if (device.is(BridgeConfig.class)) {
BridgeConfig bridgeConfig = device.as(BridgeConfig.class);
bridgeConfig.addPort(BridgeName.bridgeName(DEFAULT_BRIDGE), node.dpIntf());
} else {
log.warn("The bridging behaviour is not supported in device {}", device.id().toString());
}
} catch (ItemNotFoundException e) {
log.warn("Failed to add {} on {}", node.dpIntf(), node.hostname());
}
}
/**
* Flushes IP address from data plane interface and adds data plane IP address
* to integration bridge.
*
* @param node cordvtn node
*/
private void setIpAddress(CordVtnNode node) {
Session session = RemoteIpCommandUtil.connect(node.sshInfo());
if (session == null) {
log.debug("Failed to SSH to {}", node.hostname());
return;
}
RemoteIpCommandUtil.getCurrentIps(session, DEFAULT_BRIDGE).stream()
.filter(ip -> !ip.equals(node.localMgmtIp().ip()))
.filter(ip -> !ip.equals(node.dpIp().ip()))
.forEach(ip -> RemoteIpCommandUtil.deleteIp(session, ip, DEFAULT_BRIDGE));
boolean result = RemoteIpCommandUtil.flushIp(session, node.dpIntf()) &&
RemoteIpCommandUtil.setInterfaceUp(session, node.dpIntf()) &&
RemoteIpCommandUtil.addIp(session, node.dpIp(), DEFAULT_BRIDGE) &&
RemoteIpCommandUtil.addIp(session, node.localMgmtIp(), DEFAULT_BRIDGE) &&
RemoteIpCommandUtil.setInterfaceUp(session, DEFAULT_BRIDGE);
RemoteIpCommandUtil.disconnect(session);
if (result) {
setNodeState(node, NodeState.COMPLETE);
}
}
/**
* Checks if integration bridge exists and available.
*
* @param node cordvtn node
* @return true if the bridge is available, false otherwise
*/
private boolean isBrIntCreated(CordVtnNode node) {
return (deviceService.getDevice(node.intBrId()) != null
&& deviceService.isAvailable(node.intBrId()));
}
/**
* Checks if tunnel interface exists.
*
* @param node cordvtn node
* @return true if the interface exists, false otherwise
*/
private boolean isTunnelIntfCreated(CordVtnNode node) {
return deviceService.getPorts(node.intBrId())
.stream()
.filter(p -> getPortName(p).contains(DEFAULT_TUNNEL) &&
p.isEnabled())
.findAny().isPresent();
}
/**
* Checks if data plane interface exists.
*
* @param node cordvtn node
* @return true if the interface exists, false otherwise
*/
private boolean isDataPlaneIntfAdded(CordVtnNode node) {
return deviceService.getPorts(node.intBrId())
.stream()
.filter(p -> getPortName(p).contains(node.dpIntf()) &&
p.isEnabled())
.findAny().isPresent();
}
/**
* Checks if the IP addresses are correctly set.
*
* @param node cordvtn node
* @return true if the IP is set, false otherwise
*/
private boolean isIpAddressSet(CordVtnNode node) {
Session session = RemoteIpCommandUtil.connect(node.sshInfo());
if (session == null) {
log.debug("Failed to SSH to {}", node.hostname());
return false;
}
Set<IpAddress> intBrIps = RemoteIpCommandUtil.getCurrentIps(session, DEFAULT_BRIDGE);
boolean result = RemoteIpCommandUtil.getCurrentIps(session, node.dpIntf()).isEmpty() &&
RemoteIpCommandUtil.isInterfaceUp(session, node.dpIntf()) &&
intBrIps.contains(node.dpIp().ip()) &&
intBrIps.contains(node.localMgmtIp().ip()) &&
RemoteIpCommandUtil.isInterfaceUp(session, DEFAULT_BRIDGE);
RemoteIpCommandUtil.disconnect(session);
return result;
}
/**
* Returns connect point of a given port.
*
* @param port port
* @return connect point
*/
private ConnectPoint getConnectPoint(Port port) {
return new ConnectPoint(port.element().id(), port.number());
}
/**
* Returns connect point of a given host.
*
* @param host host
* @return connect point
*/
private ConnectPoint getConnectPoint(Host host) {
return new ConnectPoint(host.location().deviceId(), host.location().port());
}
private class OvsdbHandler implements ConnectionHandler<Device> {
@Override
public void connected(Device device) {
CordVtnNode node = getNodeByOvsdbId(device.id());
if (node != null) {
setNodeState(node, getNodeState(node));
} else {
log.debug("{} is detected on unregistered node, ignore it.", device.id());
}
}
@Override
public void disconnected(Device device) {
if (!deviceService.isAvailable(device.id())) {
log.debug("Device {} is disconnected", device.id());
adminService.removeDevice(device.id());
}
}
}
private class BridgeHandler implements ConnectionHandler<Device> {
@Override
public void connected(Device device) {
CordVtnNode node = getNodeByBridgeId(device.id());
if (node != null) {
setNodeState(node, getNodeState(node));
} else {
log.debug("{} is detected on unregistered node, ignore it.", device.id());
}
}
@Override
public void disconnected(Device device) {
CordVtnNode node = getNodeByBridgeId(device.id());
if (node != null) {
log.debug("Integration Bridge is disconnected from {}", node.hostname());
setNodeState(node, NodeState.INCOMPLETE);
}
}
/**
* Handles port added situation.
* If the added port is tunnel or data plane interface, proceed to the remaining
* node initialization. Otherwise, do nothing.
*
* @param port port
*/
public void portAdded(Port port) {
CordVtnNode node = getNodeByBridgeId((DeviceId) port.element().id());
String portName = getPortName(port);
if (node == null) {
log.debug("{} is added to unregistered node, ignore it.", portName);
return;
}
log.info("Port {} is added to {}", portName, node.hostname());
if (portName.startsWith(VPORT_PREFIX)) {
if (isNodeStateComplete(node)) {
cordVtnService.addServiceVm(node, getConnectPoint(port));
} else {
log.debug("VM is detected on incomplete node, ignore it.", portName);
}
} else if (portName.contains(DEFAULT_TUNNEL) || portName.equals(node.dpIntf())) {
setNodeState(node, getNodeState(node));
}
}
/**
* Handles port removed situation.
* If the removed port is tunnel or data plane interface, proceed to the remaining
* node initialization.Others, do nothing.
*
* @param port port
*/
public void portRemoved(Port port) {
CordVtnNode node = getNodeByBridgeId((DeviceId) port.element().id());
String portName = getPortName(port);
if (node == null) {
return;
}
log.info("Port {} is removed from {}", portName, node.hostname());
if (portName.startsWith(VPORT_PREFIX)) {
if (isNodeStateComplete(node)) {
cordVtnService.removeServiceVm(getConnectPoint(port));
} else {
log.debug("VM is vanished from incomplete node, ignore it.", portName);
}
} else if (portName.contains(DEFAULT_TUNNEL) || portName.equals(node.dpIntf())) {
setNodeState(node, NodeState.INCOMPLETE);
}
}
}
private class InternalDeviceListener implements DeviceListener {
@Override
public void event(DeviceEvent event) {
NodeId leaderNodeId = leadershipService.getLeader(appId.name());
if (!Objects.equals(localNodeId, leaderNodeId)) {
// do not allow to proceed without leadership
return;
}
Device device = event.subject();
ConnectionHandler<Device> handler =
(device.type().equals(SWITCH) ? bridgeHandler : ovsdbHandler);
switch (event.type()) {
case PORT_ADDED:
eventExecutor.execute(() -> bridgeHandler.portAdded(event.port()));
break;
case PORT_UPDATED:
if (!event.port().isEnabled()) {
eventExecutor.execute(() -> bridgeHandler.portRemoved(event.port()));
}
break;
case DEVICE_ADDED:
case DEVICE_AVAILABILITY_CHANGED:
if (deviceService.isAvailable(device.id())) {
eventExecutor.execute(() -> handler.connected(device));
} else {
eventExecutor.execute(() -> handler.disconnected(device));
}
break;
default:
break;
}
}
}
/**
* Reads cordvtn nodes from config file.
*/
private void readConfiguration() {
CordVtnConfig config = configRegistry.getConfig(appId, CordVtnConfig.class);
if (config == null) {
log.debug("No configuration found");
return;
}
config.cordVtnNodes().forEach(this::addOrUpdateNode);
}
private class InternalConfigListener implements NetworkConfigListener {
@Override
public void event(NetworkConfigEvent event) {
NodeId leaderNodeId = leadershipService.getLeader(appId.name());
if (!Objects.equals(localNodeId, leaderNodeId)) {
// do not allow to proceed without leadership
return;
}
if (!event.configClass().equals(CordVtnConfig.class)) {
return;
}
switch (event.type()) {
case CONFIG_ADDED:
case CONFIG_UPDATED:
eventExecutor.execute(CordVtnNodeManager.this::readConfiguration);
break;
default:
break;
}
}
}
private class InternalMapListener implements MapEventListener<String, CordVtnNode> {
@Override
public void event(MapEvent<String, CordVtnNode> event) {
NodeId leaderNodeId = leadershipService.getLeader(appId.name());
if (!Objects.equals(localNodeId, leaderNodeId)) {
// do not allow to proceed without leadership
return;
}
CordVtnNode oldNode;
CordVtnNode newNode;
switch (event.type()) {
case UPDATE:
oldNode = event.oldValue().value();
newNode = event.newValue().value();
if (!newNode.equals(oldNode)) {
log.info("{} has been updated", newNode.hostname());
log.debug("New node: {}", newNode);
}
// perform init procedure based on current state on any updates,
// insert, or even if the node is the same for robustness since
// it's no harm to run the init procedure multiple times
eventExecutor.execute(() -> initNode(newNode));
break;
case INSERT:
newNode = event.newValue().value();
log.info("Added {}", newNode.hostname());
eventExecutor.execute(() -> initNode(newNode));
break;
case REMOVE:
oldNode = event.oldValue().value();
log.info("{} is removed", oldNode.hostname());
break;
default:
break;
}
}
}
}
| Removing MISC, BASIC from registration, they are subset of API
Change-Id: I7e8a816a9a84b36dbd4720e3f6909c2adc99f387
| src/main/java/org/onosproject/cordvtn/impl/CordVtnNodeManager.java | Removing MISC, BASIC from registration, they are subset of API | <ide><path>rc/main/java/org/onosproject/cordvtn/impl/CordVtnNodeManager.java
<ide>
<ide> private static final KryoNamespace.Builder NODE_SERIALIZER = KryoNamespace.newBuilder()
<ide> .register(KryoNamespaces.API)
<del> .register(KryoNamespaces.MISC)
<ide> .register(CordVtnNode.class)
<ide> .register(NodeState.class)
<ide> .register(SshAccessInfo.class) |
|
Java | apache-2.0 | c0f32a572e1e1e93737e469ae15755370d7b6454 | 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-2020 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.ide.plugins.marketplace;
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl;
import com.intellij.ide.plugins.PluginNode;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Plugin repository XML parser.
* Supports both updates.xml and plugins.jetbrains.com formats.
*/
class RepositoryContentHandler extends DefaultHandler {
@NonNls private static final String CATEGORY = "category";
@NonNls private static final String PLUGIN = "plugin";
@NonNls private static final String IDEA_PLUGIN = "idea-plugin";
@NonNls private static final String NAME = "name";
@NonNls private static final String ID = "id";
@NonNls private static final String DESCRIPTION = "description";
@NonNls private static final String VERSION = "version";
@NonNls private static final String VENDOR = "vendor";
@NonNls private static final String EMAIL = "email";
@NonNls private static final String URL = "url";
@NonNls private static final String IDEA_VERSION = "idea-version";
@NonNls private static final String SINCE_BUILD = "since-build";
@NonNls private static final String UNTIL_BUILD = "until-build";
@NonNls private static final String CHANGE_NOTES = "change-notes";
@NonNls private static final String DEPENDS = "depends";
@NonNls private static final String DOWNLOADS = "downloads";
@NonNls private static final String DOWNLOAD_URL = "downloadUrl";
@NonNls private static final String DOWNLOAD_URL_NEW_STYLE = "download-url";
@NonNls private static final String SIZE = "size";
@NonNls private static final String RATING = "rating";
@NonNls private static final String DATE = "date";
@NonNls private static final String PLUGIN_UPDATED_DATE = "updatedDate";
@NonNls private static final String TAGS = "tags";
@NonNls private static final String PRODUCT_CODE = "productCode";
private final StringBuilder currentValue = new StringBuilder();
private PluginNode currentPlugin;
private List<PluginNode> plugins;
private Stack<String> categories;
private String categoryName;
@NotNull
List<PluginNode> getPluginsList() {
return plugins != null ? plugins : Collections.emptyList();
}
@Override
public void startDocument() {
plugins = new ArrayList<>();
categories = new Stack<>();
}
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals(CATEGORY)) {
String category = attributes.getValue(NAME);
if (!StringUtil.isEmptyOrSpaces(category)) {
categories.push(category);
categoryName = null;
}
}
else if (qName.equals(IDEA_PLUGIN)) {
currentPlugin = new PluginNode(PluginId.getId("unknown"));
currentPlugin.setCategory(buildCategoryName());
currentPlugin.setDownloads(attributes.getValue(DOWNLOADS));
currentPlugin.setSize(attributes.getValue(SIZE));
currentPlugin.setUrl(attributes.getValue(URL));
String dateString = attributes.getValue(PLUGIN_UPDATED_DATE) != null ? attributes.getValue(PLUGIN_UPDATED_DATE) : attributes.getValue(DATE);
if (dateString != null) {
currentPlugin.setDate(dateString);
}
currentPlugin.setIncomplete(false);
}
else if (qName.equals(IDEA_VERSION)) {
currentPlugin.setSinceBuild(attributes.getValue(SINCE_BUILD));
currentPlugin.setUntilBuild(IdeaPluginDescriptorImpl.convertExplicitBigNumberInUntilBuildToStar(attributes.getValue(UNTIL_BUILD)));
}
else if (qName.equals(VENDOR)) {
currentPlugin.setVendorEmail(attributes.getValue(EMAIL));
currentPlugin.setVendorUrl(attributes.getValue(URL));
}
else if (qName.equals(PLUGIN)) {
String id = attributes.getValue(ID);
currentPlugin = id == null ? new PluginNode(PluginId.getId("unknown")) : new PluginNode(PluginId.getId(id));
currentPlugin.setDownloadUrl(attributes.getValue(URL));
currentPlugin.setVersion(attributes.getValue(VERSION));
currentPlugin.setIncomplete(true);
}
currentValue.setLength(0);
}
@Override
public void endElement(String namespaceURI, String localName, String qName) {
String currentValueString = currentValue.toString();
currentValue.setLength(0);
if (qName.equals(ID)) {
currentPlugin.setId(currentValueString);
}
else if (qName.equals(NAME)) {
currentPlugin.setName(currentValueString);
}
else if (qName.equals(DESCRIPTION)) {
currentPlugin.setDescription(currentValueString);
}
else if (qName.equals(VERSION)) {
currentPlugin.setVersion(currentValueString);
}
else if (qName.equals(VENDOR)) {
currentPlugin.setVendor(currentValueString);
}
else if (qName.equals(DEPENDS)) {
currentPlugin.addDepends(currentValueString, false);
}
else if (qName.equals(CHANGE_NOTES)) {
currentPlugin.setChangeNotes(currentValueString);
}
else if (qName.equals(CATEGORY)) {
categories.pop();
categoryName = null;
}
else if (qName.equals(RATING)) {
currentPlugin.setRating(currentValueString);
}
else if (qName.equals(DOWNLOAD_URL) || qName.equals(DOWNLOAD_URL_NEW_STYLE)) {
currentPlugin.setDownloadUrl(currentValueString);
}
else if (qName.equals(IDEA_PLUGIN) || qName.equals(PLUGIN)) {
if (currentPlugin != null) {
plugins.add(currentPlugin);
}
currentPlugin = null;
}
else if (qName.equals(TAGS)) {
currentPlugin.addTags(currentValueString);
}
else if (qName.equals(PRODUCT_CODE)) {
currentPlugin.setProductCode(currentValueString);
}
}
@Override
public void characters(char[] ch, int start, int length) {
currentValue.append(ch, start, length);
}
@NotNull
private String buildCategoryName() {
if (categoryName == null) {
categoryName = String.join("/", categories);
}
return categoryName;
}
} | platform/platform-impl/src/com/intellij/ide/plugins/marketplace/RepositoryContentHandler.java | // Copyright 2000-2020 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.ide.plugins.marketplace;
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl;
import com.intellij.ide.plugins.PluginNode;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.zip.signer.verifier.ZipVerifier;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Plugin repository XML parser.
* Supports both updates.xml and plugins.jetbrains.com formats.
*/
class RepositoryContentHandler extends DefaultHandler {
@NonNls private static final String CATEGORY = "category";
@NonNls private static final String PLUGIN = "plugin";
@NonNls private static final String IDEA_PLUGIN = "idea-plugin";
@NonNls private static final String NAME = "name";
@NonNls private static final String ID = "id";
@NonNls private static final String DESCRIPTION = "description";
@NonNls private static final String VERSION = "version";
@NonNls private static final String VENDOR = "vendor";
@NonNls private static final String EMAIL = "email";
@NonNls private static final String URL = "url";
@NonNls private static final String IDEA_VERSION = "idea-version";
@NonNls private static final String SINCE_BUILD = "since-build";
@NonNls private static final String UNTIL_BUILD = "until-build";
@NonNls private static final String CHANGE_NOTES = "change-notes";
@NonNls private static final String DEPENDS = "depends";
@NonNls private static final String DOWNLOADS = "downloads";
@NonNls private static final String DOWNLOAD_URL = "downloadUrl";
@NonNls private static final String DOWNLOAD_URL_NEW_STYLE = "download-url";
@NonNls private static final String SIZE = "size";
@NonNls private static final String RATING = "rating";
@NonNls private static final String DATE = "date";
@NonNls private static final String PLUGIN_UPDATED_DATE = "updatedDate";
@NonNls private static final String TAGS = "tags";
@NonNls private static final String PRODUCT_CODE = "productCode";
private final StringBuilder currentValue = new StringBuilder();
private PluginNode currentPlugin;
private List<PluginNode> plugins;
private Stack<String> categories;
private String categoryName;
@NotNull
List<PluginNode> getPluginsList() {
return plugins != null ? plugins : Collections.emptyList();
}
@Override
public void startDocument() {
plugins = new ArrayList<>();
categories = new Stack<>();
}
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals(CATEGORY)) {
String category = attributes.getValue(NAME);
if (!StringUtil.isEmptyOrSpaces(category)) {
categories.push(category);
categoryName = null;
}
}
else if (qName.equals(IDEA_PLUGIN)) {
currentPlugin = new PluginNode(PluginId.getId("unknown"));
currentPlugin.setCategory(buildCategoryName());
currentPlugin.setDownloads(attributes.getValue(DOWNLOADS));
currentPlugin.setSize(attributes.getValue(SIZE));
currentPlugin.setUrl(attributes.getValue(URL));
String dateString = attributes.getValue(PLUGIN_UPDATED_DATE) != null ? attributes.getValue(PLUGIN_UPDATED_DATE) : attributes.getValue(DATE);
if (dateString != null) {
currentPlugin.setDate(dateString);
}
currentPlugin.setIncomplete(false);
}
else if (qName.equals(IDEA_VERSION)) {
currentPlugin.setSinceBuild(attributes.getValue(SINCE_BUILD));
currentPlugin.setUntilBuild(IdeaPluginDescriptorImpl.convertExplicitBigNumberInUntilBuildToStar(attributes.getValue(UNTIL_BUILD)));
}
else if (qName.equals(VENDOR)) {
currentPlugin.setVendorEmail(attributes.getValue(EMAIL));
currentPlugin.setVendorUrl(attributes.getValue(URL));
}
else if (qName.equals(PLUGIN)) {
String id = attributes.getValue(ID);
currentPlugin = id == null ? new PluginNode(PluginId.getId("unknown")) : new PluginNode(PluginId.getId(id));
currentPlugin.setDownloadUrl(attributes.getValue(URL));
currentPlugin.setVersion(attributes.getValue(VERSION));
currentPlugin.setIncomplete(true);
}
currentValue.setLength(0);
}
@Override
public void endElement(String namespaceURI, String localName, String qName) {
String currentValueString = currentValue.toString();
currentValue.setLength(0);
if (qName.equals(ID)) {
currentPlugin.setId(currentValueString);
}
else if (qName.equals(NAME)) {
currentPlugin.setName(currentValueString);
}
else if (qName.equals(DESCRIPTION)) {
currentPlugin.setDescription(currentValueString);
}
else if (qName.equals(VERSION)) {
currentPlugin.setVersion(currentValueString);
}
else if (qName.equals(VENDOR)) {
currentPlugin.setVendor(currentValueString);
}
else if (qName.equals(DEPENDS)) {
currentPlugin.addDepends(currentValueString, false);
}
else if (qName.equals(CHANGE_NOTES)) {
currentPlugin.setChangeNotes(currentValueString);
}
else if (qName.equals(CATEGORY)) {
categories.pop();
categoryName = null;
}
else if (qName.equals(RATING)) {
currentPlugin.setRating(currentValueString);
}
else if (qName.equals(DOWNLOAD_URL) || qName.equals(DOWNLOAD_URL_NEW_STYLE)) {
currentPlugin.setDownloadUrl(currentValueString);
}
else if (qName.equals(IDEA_PLUGIN) || qName.equals(PLUGIN)) {
if (currentPlugin != null) {
plugins.add(currentPlugin);
}
currentPlugin = null;
}
else if (qName.equals(TAGS)) {
currentPlugin.addTags(currentValueString);
}
else if (qName.equals(PRODUCT_CODE)) {
currentPlugin.setProductCode(currentValueString);
}
}
@Override
public void characters(char[] ch, int start, int length) {
currentValue.append(ch, start, length);
}
@NotNull
private String buildCategoryName() {
if (categoryName == null) {
categoryName = String.join("/", categories);
}
return categoryName;
}
} | remove unused import
GitOrigin-RevId: 7ea65a03fb0dddbcbd3ce34eee510da131cc774f | platform/platform-impl/src/com/intellij/ide/plugins/marketplace/RepositoryContentHandler.java | remove unused import | <ide><path>latform/platform-impl/src/com/intellij/ide/plugins/marketplace/RepositoryContentHandler.java
<ide> import com.intellij.util.containers.Stack;
<ide> import org.jetbrains.annotations.NonNls;
<ide> import org.jetbrains.annotations.NotNull;
<del>import org.jetbrains.zip.signer.verifier.ZipVerifier;
<ide> import org.xml.sax.Attributes;
<ide> import org.xml.sax.SAXException;
<ide> import org.xml.sax.helpers.DefaultHandler; |
|
JavaScript | mit | 0be9cce6c9b593ed0995efbbe4009663432c6cd7 | 0 | kera-inc/ng-transloadit | angular.module('ng-transloadit', []).factory('Transloadit', ['$http', '$rootScope', '$timeout', function($http, $rootScope, $timeout) {
$scope = $rootScope.$new();
var TRANSLOADIT_API = 'https://api2-eu-west-1.transloadit.com/assemblies';
function getExpiryDate() {
var date = new Date();
date.setHours(date.getHours() + 12);
var year = date.getUTCFullYear();
var month = zeroFill(date.getUTCMonth() + 1, 2);
var day = zeroFill(date.getUTCDate(), 2);
var hours = zeroFill(date.getUTCHours(), 2);
var minutes = zeroFill(date.getUTCMinutes(), 2);
var seconds = zeroFill(date.getUTCSeconds(), 2);
return year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds + '+00:00';
}
function zeroFill(number, width) {
width -= number.toString().length;
if (width > 0) {
return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
}
return number + ""; // always return a string
}
return {
upload: function(file, options) {
var cancelled = false;
var xhr = new XMLHttpRequest();
this._validateBrowser();
this._validateOptions(options);
this._addExpiryDate(options);
function check(assemblyUrl) {
if (cancelled) {
return false;
}
$timeout(function() {
$http.get(assemblyUrl).success(function(results) {
if (results.ok === 'ASSEMBLY_COMPLETED') {
options.uploaded(results);
} else {
check(results.assembly_ssl_url);
}
}).error(options.error);
}, 2000);
}
options.signature(function(signatureValue) {
var paramsValue = angular.toJson(options.params);
var formData = new FormData();
formData.append('params', paramsValue);
formData.append('signature', signatureValue);
formData.append(file.name, file);
xhr.open('POST', TRANSLOADIT_API, true);
xhr.onload = function(response) {
var results = angular.fromJson(this.response);
options.processing();
check(results.assembly_ssl_url);
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
options.progress(e.loaded, e.total);
}
};
xhr.send(formData);
});
return {
cancel: function() {
cancelled = true;
xhr.abort();
}
};
},
_validateBrowser: function() {
var isXHR2 = typeof new XMLHttpRequest().upload !== 'undefined';
if (!isXHR2) {
throw new Error('Transloadit will only work with XMLHttpRequest 2');
}
},
_validateOptions: function(options) {
// mandatory fields
if (!options.signature) {
throw new Error('must supply a signature function');
}
if (!options.uploaded) {
throw new Error('must supply an uploaded callback');
}
if (!options.params) {
throw new Error('must supply params');
}
if (!options.params.auth.key) {
throw new Error('must supply a key');
}
// optional fields
options.processing = options.processing || function() {};
options.progress = options.progress || function() {};
options.error = options.error || function() {};
},
_addExpiryDate: function(options) {
options.params.auth.expires = getExpiryDate();
}
};
}]);
| lib/ng-transloadit.js | angular.module('ng-transloadit', []).factory('Transloadit', ['$http', '$rootScope', '$timeout', function($http, $rootScope, $timeout) {
$scope = $rootScope.$new();
var TRANSLOADIT_API = 'https://api2-eu-west-1.transloadit.com/assemblies';
function getExpiryDate() {
var date = new Date();
date.setHours(date.getHours() + 12);
var year = date.getUTCFullYear();
var month = zeroFill(date.getUTCMonth() + 1, 2);
var day = zeroFill(date.getUTCDate(), 2);
var hours = zeroFill(date.getUTCHours(), 2);
var minutes = zeroFill(date.getUTCMinutes(), 2);
var seconds = zeroFill(date.getUTCSeconds(), 2);
return year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds + '+00:00';
}
function zeroFill(number, width) {
width -= number.toString().length;
if (width > 0) {
return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
}
return number + ""; // always return a string
}
return {
upload: function(file, options) {
var cancelled = false;
var xhr = new XMLHttpRequest();
this._validateBrowser();
this._validateOptions(options);
this._addExpiryDate(options);
function check(assemblyUrl) {
if (cancelled) {
return false;
}
$timeout(function() {
$http.get(assemblyUrl).success(function(results) {
if (results.ok === 'ASSEMBLY_COMPLETED') {
options.uploaded(results);
} else {
check(results.assembly_url);
}
}).error(options.error);
}, 2000);
}
options.signature(function(signatureValue) {
var paramsValue = angular.toJson(options.params);
var formData = new FormData();
formData.append('params', paramsValue);
formData.append('signature', signatureValue);
formData.append(file.name, file);
xhr.open('POST', TRANSLOADIT_API, true);
xhr.onload = function(response) {
var results = angular.fromJson(this.response);
options.processing();
check(results.assembly_url_ssl);
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
options.progress(e.loaded, e.total);
}
};
xhr.send(formData);
});
return {
cancel: function() {
cancelled = true;
xhr.abort();
}
};
},
_validateBrowser: function() {
var isXHR2 = typeof new XMLHttpRequest().upload !== 'undefined';
if (!isXHR2) {
throw new Error('Transloadit will only work with XMLHttpRequest 2');
}
},
_validateOptions: function(options) {
// mandatory fields
if (!options.signature) {
throw new Error('must supply a signature function');
}
if (!options.uploaded) {
throw new Error('must supply an uploaded callback');
}
if (!options.params) {
throw new Error('must supply params');
}
if (!options.params.auth.key) {
throw new Error('must supply a key');
}
// optional fields
options.processing = options.processing || function() {};
options.progress = options.progress || function() {};
options.error = options.error || function() {};
},
_addExpiryDate: function(options) {
options.params.auth.expires = getExpiryDate();
}
};
}]);
| Response value name was wrong
Uploading is now done over SSL successfully. | lib/ng-transloadit.js | Response value name was wrong | <ide><path>ib/ng-transloadit.js
<ide> if (results.ok === 'ASSEMBLY_COMPLETED') {
<ide> options.uploaded(results);
<ide> } else {
<del> check(results.assembly_url);
<add> check(results.assembly_ssl_url);
<ide> }
<ide> }).error(options.error);
<ide> }, 2000);
<ide> var results = angular.fromJson(this.response);
<ide> options.processing();
<ide>
<del> check(results.assembly_url_ssl);
<add> check(results.assembly_ssl_url);
<ide> };
<ide>
<ide> xhr.upload.onprogress = function(e) { |
|
Java | mpl-2.0 | 8bb8db5f9b5653303ece48c962ce36a53784a51b | 0 | jentfoo/litesockets,threadly/litesockets | package org.threadly.litesockets;
import java.io.IOException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import org.threadly.concurrent.NoThreadScheduler;
import org.threadly.concurrent.SubmitterExecutor;
import org.threadly.litesockets.utils.IOUtils;
import org.threadly.util.ArgumentVerifier;
import org.threadly.util.Clock;
/**
* <p>The NoThreadSocketExecuter is a simpler implementation of a {@link SocketExecuter}
* that does not create any threads. Since there are no threads operations happen on whatever thread
* calls .select(), and only 1 thread at a time should ever call it at a time. Other then
* that it should be completely thread safe.</p>
*
* <p>This is generally the implementation used by clients. It can be used for servers
* but only when not servicing many connections at once. How many connections is hardware
* and OS defendant. For an average multi-core x86 linux server I a connections not to much more
* then 1000 connections would be its limit, though alot depends on how active those connections are.</p>
*
* <p>It should also be noted that all client read/close callbacks happen on the thread that calls select().</p>
*
* @author lwahlmeier
*/
public class NoThreadSocketExecuter extends SocketExecuterCommonBase {
private final NoThreadScheduler localNoThreadScheduler;
private Selector commonSelector;
private volatile boolean wakeUp = false;
/**
* Constructs a NoThreadSocketExecuter. {@link #start()} must still be called before using it.
*/
public NoThreadSocketExecuter() {
super(new NoThreadScheduler());
localNoThreadScheduler = (NoThreadScheduler)schedulerPool;
}
/**
* This is used to wakeup the {@link Selector} assuming it was called with a timeout on it.
* Most all methods in this class that need to do a wakeup do it automatically, but
* there are situations where you might want to wake up the thread we are blocked on
* manually.
*/
public void wakeup() {
if(commonSelector != null && commonSelector.isOpen()) {
wakeUp = true;
commonSelector.wakeup();
}
}
@Override
public void setClientOperations(final Client client) {
ArgumentVerifier.assertNotNull(client, "Client");
if(!clients.containsKey(client.getChannel())) {
return;
}
if(client.isClosed()) {
clients.remove(client.getChannel());
schedulerPool.submit(new RemoveFromSelector(commonSelector, client)).addListener(new Runnable() {
@Override
public void run() {
IOUtils.closeQuietly(client.getChannel());
}});
} else if(client.getChannel().isConnectionPending()) {
schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_CONNECT));
} else if(client.canWrite() && client.canRead()) {
schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_WRITE|SelectionKey.OP_READ));
} else if (client.canRead()){
schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_READ));
} else if (client.canWrite()){
schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_WRITE));
} else {
schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, 0));
}
commonSelector.wakeup();
}
@Override
public void setUDPServerOperations(final UDPServer udpServer, final boolean enable) {
if(checkServer(udpServer)) {
if(enable) {
if(udpServer.needsWrite()) {
schedulerPool.execute(new AddToSelector(schedulerPool, udpServer, commonSelector, SelectionKey.OP_READ|SelectionKey.OP_WRITE));
} else {
schedulerPool.execute(new AddToSelector(schedulerPool, udpServer, commonSelector, SelectionKey.OP_READ));
}
} else {
schedulerPool.execute(new AddToSelector(schedulerPool, udpServer, commonSelector, 0));
}
commonSelector.wakeup();
}
}
@Override
protected void startupService() {
commonSelector = openSelector();
this.acceptSelector = commonSelector;
this.readSelector = commonSelector;
this.writeSelector = commonSelector;
}
@Override
protected void shutdownService() {
commonSelector.wakeup();
for(final Client client: clients.values()) {
IOUtils.closeQuietly(client);
}
for(final Server server: servers.values()) {
IOUtils.closeQuietly(server);
}
if(commonSelector != null && commonSelector.isOpen()) {
closeSelector(schedulerPool, commonSelector);
}
while(localNoThreadScheduler.hasTaskReadyToRun()) {
try {
localNoThreadScheduler.tick(null);
} catch(Exception e) {
}
}
clients.clear();
servers.clear();
}
/**
* This will run all ExecuterTasks, check for pending network operations,
* then run those operations. There can be a lot of I/O operations so this
* could take some time to run. In general it should not be called from things like
* GUI threads.
*
*/
public void select() {
select(0);
}
/**
* This is the same as the {@link #select()} but it allows you to set a delay.
* This delay is the time to wait for socket operations to happen. It will
* block the calling thread for up to this amount of time, but it could be less
* if any network operation happens (including another thread adding a client/server).
*
*
* @param delay Max time in milliseconds to block for.
*/
public void select(final int delay) {
ArgumentVerifier.assertNotNegative(delay, "delay");
checkRunning();
long startTime = delay == 0 ? -1 : Clock.accurateForwardProgressingMillis();
do {
if (wakeUp) {
break;
}
try {
commonSelector.selectNow(); //We have to do this before we tick for windows
localNoThreadScheduler.tick(null);
commonSelector.select(Math.min(delay, 50));
if(isRunning()) {
for(final SelectionKey key: commonSelector.selectedKeys()) {
try {
if(key.isAcceptable()) {
doServerAccept(servers.get(key.channel()));
} else {
final Client tmpClient = clients.get(key.channel());
if(key.isConnectable() && tmpClient != null) {
doClientConnect(tmpClient, commonSelector);
key.cancel(); //Stupid windows bug here.
setClientOperations(tmpClient);
} else {
if (key.isReadable()) {
if(tmpClient != null){
doClientRead(tmpClient, commonSelector);
} else {
final Server server = servers.get(key.channel());
if(server != null && server.getServerType() == WireProtocol.UDP) {
server.acceptChannel((DatagramChannel)server.getSelectableChannel());
}
}
}
if(key.isWritable()) {
if(tmpClient != null){
doClientWrite(tmpClient, commonSelector);
} else {
final Server server = servers.get(key.channel());
if(server != null) {
if(server instanceof UDPServer) {
UDPServer us = (UDPServer) server;
stats.addWrite(us.doWrite());
setUDPServerOperations(us, true);
}
}
}
}
}
}
} catch(CancelledKeyException e) {
//Key could be cancelled at any point, we dont really care about it.
}
}
//Also for windows bug, canceled keys are not removed till we select again.
//So we just have to at the end of the loop.
commonSelector.selectNow();
localNoThreadScheduler.tick(null);
}
} catch (IOException e) {
//There is really nothing to do here but try again, usually this is because of shutdown.
} catch(ClosedSelectorException e) {
//We do nothing here because the next loop should not happen now.
} catch (NullPointerException e) {
//There is a bug in some JVMs around this where the select() can throw an NPE from native code.
}
} while ((delay == 0 ? Clock.lastKnownForwardProgressingMillis() : Clock.accurateForwardProgressingMillis()) - startTime <= delay && isRunning());
wakeUp = false;
}
@Override
public SubmitterExecutor getExecutorFor(final Object obj) {
return localNoThreadScheduler;
}
}
| src/main/java/org/threadly/litesockets/NoThreadSocketExecuter.java | package org.threadly.litesockets;
import java.io.IOException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import org.threadly.concurrent.NoThreadScheduler;
import org.threadly.concurrent.SubmitterExecutor;
import org.threadly.litesockets.utils.IOUtils;
import org.threadly.util.ArgumentVerifier;
import org.threadly.util.Clock;
/**
* <p>The NoThreadSocketExecuter is a simpler implementation of a {@link SocketExecuter}
* that does not create any threads. Since there are no threads operations happen on whatever thread
* calls .select(), and only 1 thread at a time should ever call it at a time. Other then
* that it should be completely thread safe.</p>
*
* <p>This is generally the implementation used by clients. It can be used for servers
* but only when not servicing many connections at once. How many connections is hardware
* and OS defendant. For an average multi-core x86 linux server I a connections not to much more
* then 1000 connections would be its limit, though alot depends on how active those connections are.</p>
*
* <p>It should also be noted that all client read/close callbacks happen on the thread that calls select().</p>
*
* @author lwahlmeier
*/
public class NoThreadSocketExecuter extends SocketExecuterCommonBase {
private final NoThreadScheduler localNoThreadScheduler;
private Selector commonSelector;
private volatile boolean wakeUp = false;
/**
* Constructs a NoThreadSocketExecuter. {@link #start()} must still be called before using it.
*/
public NoThreadSocketExecuter() {
super(new NoThreadScheduler());
localNoThreadScheduler = (NoThreadScheduler)schedulerPool;
}
/**
* This is used to wakeup the {@link Selector} assuming it was called with a timeout on it.
* Most all methods in this class that need to do a wakeup do it automatically, but
* there are situations where you might want to wake up the thread we are blocked on
* manually.
*/
public void wakeup() {
if(commonSelector != null && commonSelector.isOpen()) {
wakeUp = true;
commonSelector.wakeup();
}
}
@Override
public void setClientOperations(final Client client) {
ArgumentVerifier.assertNotNull(client, "Client");
if(!clients.containsKey(client.getChannel())) {
return;
}
if(client.isClosed()) {
clients.remove(client.getChannel());
schedulerPool.submit(new RemoveFromSelector(commonSelector, client)).addListener(new Runnable() {
@Override
public void run() {
IOUtils.closeQuietly(client.getChannel());
}});
} else if(client.getChannel().isConnectionPending()) {
schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_CONNECT));
} else if(client.canWrite() && client.canRead()) {
schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_WRITE|SelectionKey.OP_READ));
} else if (client.canRead()){
schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_READ));
} else if (client.canWrite()){
schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_WRITE));
} else {
schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, 0));
}
commonSelector.wakeup();
}
@Override
public void setUDPServerOperations(final UDPServer udpServer, final boolean enable) {
if(checkServer(udpServer)) {
if(enable) {
if(udpServer.needsWrite()) {
schedulerPool.execute(new AddToSelector(schedulerPool, udpServer, commonSelector, SelectionKey.OP_READ|SelectionKey.OP_WRITE));
} else {
schedulerPool.execute(new AddToSelector(schedulerPool, udpServer, commonSelector, SelectionKey.OP_READ));
}
} else {
schedulerPool.execute(new AddToSelector(schedulerPool, udpServer, commonSelector, 0));
}
commonSelector.wakeup();
}
}
@Override
protected void startupService() {
commonSelector = openSelector();
this.acceptSelector = commonSelector;
this.readSelector = commonSelector;
this.writeSelector = commonSelector;
}
@Override
protected void shutdownService() {
commonSelector.wakeup();
for(final Client client: clients.values()) {
IOUtils.closeQuietly(client);
}
for(final Server server: servers.values()) {
IOUtils.closeQuietly(server);
}
if(commonSelector != null && commonSelector.isOpen()) {
closeSelector(schedulerPool, commonSelector);
}
while(localNoThreadScheduler.hasTaskReadyToRun()) {
try {
localNoThreadScheduler.tick(null);
} catch(Exception e) {
}
}
clients.clear();
servers.clear();
}
/**
* This will run all ExecuterTasks, check for pending network operations,
* then run those operations. There can be a lot of I/O operations so this
* could take some time to run. In general it should not be called from things like
* GUI threads.
*
*/
public void select() {
select(0);
}
/**
* This is the same as the {@link #select()} but it allows you to set a delay.
* This delay is the time to wait for socket operations to happen. It will
* block the calling thread for up to this amount of time, but it could be less
* if any network operation happens (including another thread adding a client/server).
*
*
* @param delay Max time in milliseconds to block for.
*/
public void select(final int delay) {
ArgumentVerifier.assertNotNegative(delay, "delay");
checkRunning();
long startTime = Clock.accurateForwardProgressingMillis();
while(Clock.accurateForwardProgressingMillis()- startTime <= delay && isRunning() && !wakeUp) {
try {
commonSelector.selectNow(); //We have to do this before we tick for windows
localNoThreadScheduler.tick(null);
commonSelector.select(Math.min(delay, 50));
if(isRunning()) {
for(final SelectionKey key: commonSelector.selectedKeys()) {
try {
if(key.isAcceptable()) {
doServerAccept(servers.get(key.channel()));
} else {
final Client tmpClient = clients.get(key.channel());
if(key.isConnectable() && tmpClient != null) {
doClientConnect(tmpClient, commonSelector);
key.cancel(); //Stupid windows bug here.
setClientOperations(tmpClient);
} else {
if (key.isReadable()) {
if(tmpClient != null){
doClientRead(tmpClient, commonSelector);
} else {
final Server server = servers.get(key.channel());
if(server != null && server.getServerType() == WireProtocol.UDP) {
server.acceptChannel((DatagramChannel)server.getSelectableChannel());
}
}
}
if(key.isWritable()) {
if(tmpClient != null){
doClientWrite(tmpClient, commonSelector);
} else {
final Server server = servers.get(key.channel());
if(server != null) {
if(server instanceof UDPServer) {
UDPServer us = (UDPServer) server;
stats.addWrite(us.doWrite());
setUDPServerOperations(us, true);
}
}
}
}
}
}
} catch(CancelledKeyException e) {
//Key could be cancelled at any point, we dont really care about it.
}
}
//Also for windows bug, canceled keys are not removed till we select again.
//So we just have to at the end of the loop.
commonSelector.selectNow();
localNoThreadScheduler.tick(null);
}
} catch (IOException e) {
//There is really nothing to do here but try again, usually this is because of shutdown.
} catch(ClosedSelectorException e) {
//We do nothing here because the next loop should not happen now.
} catch (NullPointerException e) {
//There is a bug in some JVMs around this where the select() can throw an NPE from native code.
}
}
wakeUp = false;
}
@Override
public SubmitterExecutor getExecutorFor(final Object obj) {
return localNoThreadScheduler;
}
}
| NoThreadSocketExecuter: Fix for possible missed select() execution
| src/main/java/org/threadly/litesockets/NoThreadSocketExecuter.java | NoThreadSocketExecuter: Fix for possible missed select() execution | <ide><path>rc/main/java/org/threadly/litesockets/NoThreadSocketExecuter.java
<ide> public void select(final int delay) {
<ide> ArgumentVerifier.assertNotNegative(delay, "delay");
<ide> checkRunning();
<del> long startTime = Clock.accurateForwardProgressingMillis();
<del> while(Clock.accurateForwardProgressingMillis()- startTime <= delay && isRunning() && !wakeUp) {
<add> long startTime = delay == 0 ? -1 : Clock.accurateForwardProgressingMillis();
<add> do {
<add> if (wakeUp) {
<add> break;
<add> }
<ide> try {
<ide> commonSelector.selectNow(); //We have to do this before we tick for windows
<ide> localNoThreadScheduler.tick(null);
<ide> } catch (NullPointerException e) {
<ide> //There is a bug in some JVMs around this where the select() can throw an NPE from native code.
<ide> }
<del> }
<add> } while ((delay == 0 ? Clock.lastKnownForwardProgressingMillis() : Clock.accurateForwardProgressingMillis()) - startTime <= delay && isRunning());
<ide> wakeUp = false;
<ide> }
<ide> |
|
Java | mit | f7156be0f99fb1eaf7d815d48e0f1c7abaffcfe3 | 0 | aikar/TaskChain,aikar/TaskChain | /*
* Copyright (c) 2016 Daniel Ennis (Aikar) - MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.aikar.taskchain;
import co.aikar.taskchain.TaskChainTasks.Task;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
class SharedTaskChain<R> extends TaskChain<R> {
private final String name;
private final Map<String, Queue<SharedTaskChain>> sharedChains;
private Queue<SharedTaskChain> queue;
private volatile boolean isPending;
private volatile boolean canExecute = true;
SharedTaskChain(String name, TaskChainFactory factory) {
super(factory);
this.sharedChains = factory.getSharedChains();
this.name = name;
synchronized (this.sharedChains) {
this.queue = sharedChains.get(this.name);
if (this.queue == null) {
this.queue = new ConcurrentLinkedQueue<>();
this.sharedChains.put(this.name, this.queue);
}
this.queue.add(this);
}
}
@Override
public void execute(Consumer<Boolean> done, BiConsumer<Exception, Task<?, ?>> errorHandler) {
this.setErrorHandler(errorHandler);
this.setDoneCallback((finished) -> {
this.setDoneCallback(done);
this.done(finished);
processQueue();
});
boolean shouldExecute;
synchronized (this.sharedChains) {
this.isPending = this.queue.peek() != this;
shouldExecute = !this.isPending && this.canExecute;
if (shouldExecute) {
this.canExecute = false;
}
}
if (shouldExecute) {
execute0();
}
}
/**
* Launches the next TaskChain in the queue if it is ready, or cleans up the queue if nothing left to do.
*/
private void processQueue() {
this.queue.poll(); // Remove self
final SharedTaskChain next;
synchronized (this.sharedChains) {
next = this.queue.peek();
if (next == null) {
this.sharedChains.remove(this.name);
return;
}
if (!next.isPending) {
// Created but wasn't executed yet. Wait until the chain executes itself.
return;
}
this.canExecute = false;
}
next.execute0();
}
}
| core/src/main/java/co/aikar/taskchain/SharedTaskChain.java | /*
* Copyright (c) 2016 Daniel Ennis (Aikar) - MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.aikar.taskchain;
import co.aikar.taskchain.TaskChainTasks.Task;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
class SharedTaskChain<R> extends TaskChain<R> {
private final String name;
private final Map<String, Queue<SharedTaskChain>> sharedChains;
private Queue<SharedTaskChain> queue;
private volatile boolean isPending;
SharedTaskChain(String name, TaskChainFactory factory) {
super(factory);
this.sharedChains = factory.getSharedChains();
this.name = name;
synchronized (this.sharedChains) {
this.queue = sharedChains.get(this.name);
if (this.queue == null) {
this.queue = new ConcurrentLinkedQueue<>();
this.sharedChains.put(this.name, this.queue);
}
this.queue.add(this);
}
}
@Override
public void execute(Consumer<Boolean> done, BiConsumer<Exception, Task<?, ?>> errorHandler) {
this.setErrorHandler(errorHandler);
this.setDoneCallback((finished) -> {
this.setDoneCallback(done);
this.done(finished);
processQueue();
});
synchronized (this.sharedChains) {
this.isPending = this.queue.peek() != this;
}
if (!this.isPending) {
execute0();
}
}
/**
* Launches the next TaskChain in the queue if it is ready, or cleans up the queue if nothing left to do.
*/
private void processQueue() {
this.queue.poll(); // Remove self
final SharedTaskChain next;
synchronized (this.sharedChains) {
next = this.queue.peek();
if (next == null) {
this.sharedChains.remove(this.name);
return;
}
if (!next.isPending) {
// Created but wasn't executed yet. Wait until the chain executes itself.
return;
}
}
next.execute0();
}
}
| more concurrency fixes
after last fix, I studied code some more and saw room for another issue
| core/src/main/java/co/aikar/taskchain/SharedTaskChain.java | more concurrency fixes | <ide><path>ore/src/main/java/co/aikar/taskchain/SharedTaskChain.java
<ide> private final Map<String, Queue<SharedTaskChain>> sharedChains;
<ide> private Queue<SharedTaskChain> queue;
<ide> private volatile boolean isPending;
<add> private volatile boolean canExecute = true;
<ide>
<ide> SharedTaskChain(String name, TaskChainFactory factory) {
<ide> super(factory);
<ide> processQueue();
<ide> });
<ide>
<add> boolean shouldExecute;
<ide> synchronized (this.sharedChains) {
<ide> this.isPending = this.queue.peek() != this;
<add> shouldExecute = !this.isPending && this.canExecute;
<add> if (shouldExecute) {
<add> this.canExecute = false;
<add> }
<ide> }
<del> if (!this.isPending) {
<add> if (shouldExecute) {
<ide> execute0();
<ide> }
<ide> }
<ide> // Created but wasn't executed yet. Wait until the chain executes itself.
<ide> return;
<ide> }
<add> this.canExecute = false;
<ide> }
<ide>
<ide> next.execute0(); |
|
Java | mpl-2.0 | 595f993b482213dbefd155bf8789305c92c598dc | 0 | Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV | package org.helioviewer.gl3d.camera;
public class GL3DSpaceObject {
private final String urlName;
private final String labelName;
private static GL3DSpaceObject objectList[];
public static GL3DSpaceObject[] getObjectList() {
if (objectList == null) {
createObjectList();
}
return objectList;
}
private static void createObjectList() {
objectList = new GL3DSpaceObject[11];
objectList[0] = new GL3DSpaceObject("Mercury", "Mercury");
objectList[1] = new GL3DSpaceObject("Venus", "Venus");
objectList[2] = new GL3DSpaceObject("Earth", "Earth");
objectList[3] = new GL3DSpaceObject("Moon", "Moon");
objectList[4] = new GL3DSpaceObject("Mars", "Mars");
objectList[5] = new GL3DSpaceObject("Saturn%20Barycenter", "Saturn");
objectList[6] = new GL3DSpaceObject("Uranus%20Barycenter", "Uranus");
objectList[7] = new GL3DSpaceObject("Neptune%20Barycenter", "Neptune");
objectList[8] = new GL3DSpaceObject("Jupiter%20Barycenter", "Jupiter");
objectList[9] = new GL3DSpaceObject("Pluto%20Barycenter", "Pluto");
objectList[10] = new GL3DSpaceObject("Solar%20Orbiter", "Solar Orbiter");
}
private GL3DSpaceObject(String urlName, String labelName) {
this.urlName = urlName;
this.labelName = labelName;
}
public String getUrlName() {
return this.urlName;
}
@Override
public String toString() {
return this.labelName;
}
}
| src/jhv/src/org/helioviewer/gl3d/camera/GL3DSpaceObject.java | package org.helioviewer.gl3d.camera;
public class GL3DSpaceObject {
private final String urlName;
private final String labelName;
private static GL3DSpaceObject objectList[];
public static GL3DSpaceObject[] getObjectList() {
if (objectList == null) {
createObjectList();
}
return objectList;
}
private static void createObjectList() {
objectList = new GL3DSpaceObject[9];
objectList[0] = new GL3DSpaceObject("Mercury", "Mercury");
objectList[1] = new GL3DSpaceObject("Venus", "Venus");
objectList[2] = new GL3DSpaceObject("Earth", "Earth");
objectList[3] = new GL3DSpaceObject("Mars", "Mars");
objectList[4] = new GL3DSpaceObject("Saturn", "Saturn");
objectList[5] = new GL3DSpaceObject("Uranus", "Uranus");
objectList[6] = new GL3DSpaceObject("Jupiter", "Jupiter");
objectList[7] = new GL3DSpaceObject("Pluto", "Pluto");
objectList[8] = new GL3DSpaceObject("Solar%20Orbiter", "Solar Orbiter");
}
private GL3DSpaceObject(String urlName, String labelName) {
this.urlName = urlName;
this.labelName = labelName;
}
public String getUrlName() {
return this.urlName;
}
@Override
public String toString() {
return this.labelName;
}
}
| fix outer planets, add moon
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@1559 b4e469a2-07ce-4b26-9273-4d7d95a670c7
| src/jhv/src/org/helioviewer/gl3d/camera/GL3DSpaceObject.java | fix outer planets, add moon | <ide><path>rc/jhv/src/org/helioviewer/gl3d/camera/GL3DSpaceObject.java
<ide> }
<ide>
<ide> private static void createObjectList() {
<del> objectList = new GL3DSpaceObject[9];
<add> objectList = new GL3DSpaceObject[11];
<ide> objectList[0] = new GL3DSpaceObject("Mercury", "Mercury");
<ide> objectList[1] = new GL3DSpaceObject("Venus", "Venus");
<ide> objectList[2] = new GL3DSpaceObject("Earth", "Earth");
<del> objectList[3] = new GL3DSpaceObject("Mars", "Mars");
<del> objectList[4] = new GL3DSpaceObject("Saturn", "Saturn");
<del> objectList[5] = new GL3DSpaceObject("Uranus", "Uranus");
<del> objectList[6] = new GL3DSpaceObject("Jupiter", "Jupiter");
<del> objectList[7] = new GL3DSpaceObject("Pluto", "Pluto");
<del> objectList[8] = new GL3DSpaceObject("Solar%20Orbiter", "Solar Orbiter");
<add> objectList[3] = new GL3DSpaceObject("Moon", "Moon");
<add>
<add> objectList[4] = new GL3DSpaceObject("Mars", "Mars");
<add> objectList[5] = new GL3DSpaceObject("Saturn%20Barycenter", "Saturn");
<add> objectList[6] = new GL3DSpaceObject("Uranus%20Barycenter", "Uranus");
<add> objectList[7] = new GL3DSpaceObject("Neptune%20Barycenter", "Neptune");
<add>
<add> objectList[8] = new GL3DSpaceObject("Jupiter%20Barycenter", "Jupiter");
<add> objectList[9] = new GL3DSpaceObject("Pluto%20Barycenter", "Pluto");
<add> objectList[10] = new GL3DSpaceObject("Solar%20Orbiter", "Solar Orbiter");
<ide> }
<ide>
<ide> private GL3DSpaceObject(String urlName, String labelName) { |
|
Java | apache-2.0 | 9f5256f2083c15714e4044c9230e49ae1737b38e | 0 | javaito/HolandaCatalinaFw,kevchuk/HolandaCatalinaFw,nojustiniano/HolandaCatalinaFw,javaito/HolandaCatalinaFw,nojustiniano/HolandaCatalinaFw,javaito/HolandaCatalinaFw | import org.hcjf.io.net.http.*;
import org.hcjf.log.Log;
import org.hcjf.properties.SystemProperties;
/**
* Created by javaito on 15/1/2016.
*/
public class Main {
public static void main(String[] args) throws Exception {
// Log.d("", "Hola mundo!!");
//
// Log.d("", "Hola, excepcion!!", new NullPointerException());
//
// SystemProperties.get("bla", V -> (V.length() == 4));
HttpServer server = new HttpServer(1338);
server.addContext(new Context(".*") {
@Override
public HttpResponse onContext(HttpRequest request) {
byte[] body = "Hello world!!".getBytes();
HttpResponse response = new HttpResponse();
response.setResponseCode(200);
response.setBody(body);
response.addHeader(new HttpHeader(HttpHeader.CONTENT_LENGTH, Integer.toString(body.length)));
return response;
}
@Override
protected HttpResponse onError(HttpRequest request, Throwable throwable) {
return null;
}
});
server.start();
}
}
| test/Main.java | import org.hcjf.log.Log;
import org.hcjf.properties.SystemProperties;
/**
* Created by javaito on 15/1/2016.
*/
public class Main {
public static void main(String[] args) throws Exception {
Log.d("", "Hola mundo!!");
Log.d("", "Hola, excepcion!!", new NullPointerException());
SystemProperties.get("bla", V -> (V.length() == 4));
}
}
| Add stress http server testing
| test/Main.java | Add stress http server testing | <ide><path>est/Main.java
<add>import org.hcjf.io.net.http.*;
<ide> import org.hcjf.log.Log;
<ide> import org.hcjf.properties.SystemProperties;
<ide>
<ide> public class Main {
<ide>
<ide> public static void main(String[] args) throws Exception {
<del> Log.d("", "Hola mundo!!");
<add>// Log.d("", "Hola mundo!!");
<add>//
<add>// Log.d("", "Hola, excepcion!!", new NullPointerException());
<add>//
<add>// SystemProperties.get("bla", V -> (V.length() == 4));
<ide>
<del> Log.d("", "Hola, excepcion!!", new NullPointerException());
<ide>
<del> SystemProperties.get("bla", V -> (V.length() == 4));
<add> HttpServer server = new HttpServer(1338);
<add> server.addContext(new Context(".*") {
<add> @Override
<add> public HttpResponse onContext(HttpRequest request) {
<add> byte[] body = "Hello world!!".getBytes();
<add> HttpResponse response = new HttpResponse();
<add> response.setResponseCode(200);
<add> response.setBody(body);
<add> response.addHeader(new HttpHeader(HttpHeader.CONTENT_LENGTH, Integer.toString(body.length)));
<add> return response;
<add> }
<add>
<add> @Override
<add> protected HttpResponse onError(HttpRequest request, Throwable throwable) {
<add> return null;
<add> }
<add> });
<add> server.start();
<add>
<ide> }
<ide>
<ide> } |
|
JavaScript | bsd-3-clause | cb716e297d21469a0bdbc863817d038e36868358 | 0 | FreifunkMD/ffmap-backend,FreifunkBremen/ffmap-backend,FreifunkBremen/ffmap-backend,freifunk-kiel/ffmap-backend,freifunk-mwu/ffmap-backend,FreiFunkMuenster/ffmap-backend,rubo77/ffmap-backend,freifunkhamburg/ffmap-backend,FreiFunkMuenster/ffmap-backend,ff-kbu/ffmap-backend,ffnord/ffmap-backend,kpcyrd/ffmap-backend,FreifunkMD/ffmap-backend,FreifunkJena/ffmap-backend,freifunk-mwu/ffmap-backend,ff-kbu/ffmap-backend,ffnord/ffmap-backend,ffac/ffmap-backend,mweinelt/ffmap-backend,freifunkhamburg/ffmap-backend,freifunk-fulda/ffmap-backend | var style;
function switch_style(s) {
var el = document.getElementsByTagName("link")
for (var i = 0; i < el.length; i++ ) {
if (el[i].getAttribute("rel").indexOf("style") != -1
&& el[i].getAttribute("title")) {
if (el[i].getAttribute("title") == s) {
style_btn.text(s)
el[i].disabled = false
} else
el[i].disabled = true
}
}
}
function getOffset( el ) {
var _x = 0, _y = 0
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft
_y += el.offsetTop - el.scrollTop
el = el.offsetParent
}
return { top: _y, left: _x }
}
var offset = getOffset(document.getElementById('chart'))
var w, h
resize()
window.onresize = resize
function resize() {
var offset = getOffset(document.getElementById('chart'))
w = window.innerWidth - offset.left
h = window.innerHeight - offset.top - 1
d3.select("#chart")
.attr("width", w).attr("height", h)
if (vis)
vis.attr("width", w).attr("height", h)
if (force)
force.size([w, h]).start()
}
function next_style() {
var s;
if (style !== undefined)
s = d3.select("head link[title=" + style + "] + link")
if (s == null || s[0][0] == null)
s = d3.select("head link[title]")
style = s[0][0].getAttribute("title")
switch_style(style)
}
var cp = d3.select("header").append("div")
.attr("id", "controlpanel")
var updated_at = cp.append("p")
cp.append("button")
.attr("class", "btn")
.attr("value", "reload")
.text("Aktualisieren")
.on("click", reload)
var style_btn = cp.append("button")
.attr("class", "btn")
.attr("value", "reload")
.text("Farbwechsler")
.on("click", next_style)
cp.append("button")
.attr("class", "btn")
.attr("value", "reload")
.on("click", pacman)
.append("svg")
.attr("width", 12)
.attr("height", 12)
.append("path")
.attr("d", d3.svg.arc().innerRadius(0)
.outerRadius(5)
.endAngle(-Math.PI/4 + Math.PI/2 + 2*Math.PI)
.startAngle(Math.PI/4 + Math.PI/2))
.attr("fill", "#888")
.attr("transform", "translate(6,7)")
var btns = cp.append("div")
.attr("class", "btn-group")
btns.append("button")
.attr("class", "btn active left")
.attr("value", "clients")
.text("Clients")
.on("click", update_graph)
btns.append("button")
.attr("class", "btn active right")
.attr("value", "vpn")
.text("VPN")
.on("click", update_graph)
var meshinfo = d3.select("sidebar")
.insert("div", ":first-child")
meshinfo.append("h2").text("Mesh")
meshinfo.append("p")
.attr("id", "nodecount")
meshinfo.append("p")
.attr("id", "gatewaycount")
meshinfo.append("p")
.attr("id", "clientcount")
//cp.append("input")
// .on("keyup", function(){show_node(this.value)})
// .on("change", function(){show_node(this.value)})
function show_node(mac) {
d3.selectAll("#chart .node")
.classed("marked", false)
if (mac.length == 0)
return
d3.selectAll("#chart .node")
.each( function(d) {
if (d.id == mac)
d3.select(this)
.classed("marked", true)
})
}
var hashstr = window.location.hash.substring(1)
function isConnected(a, b) {
return linkedByIndex[a.index + "," + b.index] ||
linkedByIndex[b.index + "," + a.index] ||
a.index == b.index
}
function fade(opacity) {
return function(d) {
vis.selectAll("g.node")
.style("stroke-opacity", function(o) {
var connected = isConnected(d, o)
if (connected && opacity != 1)
d3.select(this)
.classed("highlight", true)
else
d3.select(this)
.classed("highlight", false)
thisOpacity = connected?1:opacity
this.setAttribute('fill-opacity', thisOpacity)
return thisOpacity
})
vis.selectAll(".link *")
.style("stroke-opacity", function(o) {
return o.source === d || o.target === d ? 1 : opacity
})
}
}
function show_node_info(d) {
d3.selectAll("#nodeinfo").remove()
nodeinfo = d3.select("#chart")
.append("div")
.attr("id", "nodeinfo")
nodeinfo.append("button")
.attr("class", "close")
.text("x")
.on("click", function(d) {
nodeinfo.remove()
})
nodeinfo.append("h1")
.text(d.name + " / " + d.id)
nodeinfo.append("p")
.append("label")
.text("macs: " + d.macs)
if (d.geo) {
nodeinfo.append("h2").text("Geodaten")
nodeinfo.append("p")
.text(d.geo)
url = GMaps.staticMapURL({
size: [300, 100],
lat: d.geo[0],
lng: d.geo[1],
markers: [
{lat: d.geo[0], lng: d.geo[1]}
]
})
nodeinfo.append("img")
.attr("src", url)
}
}
function update_graph() {
jQuery(this).toggleClass("active")
var value = jQuery(this).val()
visible[value] = jQuery(this).hasClass("active")
update()
}
var vis = d3.select("#chart").append("svg")
.attr("width", w)
.attr("height", h)
vis.append("g").attr("class", "links")
vis.append("g").attr("class", "nodes")
var linkedByIndex
var force = d3.layout.force()
.charge( function (d) {
if (d.flags.client)
return -30
return -200
})
.gravity(0.035)
.friction(0.73)
.theta(0.8)
.size([w, h])
.linkDistance(function (d) {
switch (d.type) {
case "vpn": return 200
case "client": return 20
default: return 70
}
})
.linkStrength(function (d) {
switch (d.type) {
case "vpn": return 0.05
case "client": return 1
default: return 0.8
}
})
force.on("tick", function() {
var size = force.size()
var nodes = force.nodes()
var n = nodes.length
for (i = 0; i < n; i++) {
var o = nodes[i]
if (!o.fixed) {
node = d3.select(document.getElementById(o.id))[0][0]
box = bounding_box(node)
if (o.x < box.rx) o.x = box.rx
if (o.x > size[0] - box.rx) o.x = size[0] - box.rx
if (o.y < box.ry) o.y = box.ry
if (o.y > size[1] - box.ry) o.y = size[1] - box.ry
}
}
var link = vis.selectAll(".link")
link.selectAll("line")
.attr("x1", function(d) { return d.source.x })
.attr("y1", function(d) { return d.source.y })
.attr("x2", function(d) { return d.target.x })
.attr("y2", function(d) { return d.target.y })
vis.selectAll(".node").attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
})
var data
var visible = {clients: true, vpn: true}
function reload() {
d3.json("nodes.json", function(json) {
// update existing nodes with new info
// XXX inefficient data structure
json.nodes.forEach(function(d, i) {
var n
force.nodes().forEach(function(x) {if (x.id == d.id) n = x})
if (n) {
for (var key in d)
if (d.hasOwnProperty(key))
n[key] = d[key]
json.nodes[i] = n
}
})
json.links.forEach(function(d, i) {
var n
force.links().forEach(function(x) {if (x.id == d.id) n = x})
if (n) {
for (var key in d)
if (d.hasOwnProperty(key))
n[key] = d[key]
json.links[i] = n
}
})
// replace indices with real objects
json.links.forEach( function(d) {
if (typeof d.source == "number") d.source = json.nodes[d.source];
if (typeof d.target == "number") d.target = json.nodes[d.target];
})
// count vpn links
json.nodes.forEach(function(d) {
d.vpns = 0
})
json.links.forEach(function(d) {
var node, other
if (d.type == "vpn") {
d.source.vpns++
d.target.vpns++
}
})
data = json
updated_at.text(d3.time.format("%X")(new Date()))
var nNodes = data.nodes.filter(function(d) {
return !d.flags.client && d.flags.online
}).length,
nGateways = data.nodes.filter(function(d) {
return d.flags.gateway && d.flags.online
}).length,
nClients = data.nodes.filter(function(d) {
return d.flags.client && d.flags.online
}).length
d3.select("#nodecount")
.text(nNodes + " Knoten")
d3.select("#gatewaycount")
.text(nGateways + " Gateways")
d3.select("#clientcount")
.text("ungefähr " + (nClients - nNodes) + " Clients")
update()
})
}
var linkcolor = d3.scale.linear()
.domain([1, 1.5, 3])
.range(["#0a3", "orange", "red"]);
function update() {
var links = data.links
.filter(function (d) {
if (!visible.vpn && d.type == "vpn")
return false
if (!visible.clients && (d.source.flags.client || d.target.flags.client))
return false
// hides links to clients
if (!visible.vpn && (d.source.flags.vpn || d.target.flags.vpn))
return false
return true
})
var link = vis.select("g.links")
.selectAll("g.link")
.data(links, function(d) {
return d.id
})
var linkEnter = link.enter().append("g")
.attr("class", function(d) {
return "link " + d.type
})
.on("mouseover", function(d) {
d.source.fixed |= 2
d.target.fixed |= 2
})
.on("mouseout", function(d) {
d.source.fixed &= 1
d.target.fixed &= 1
})
linkEnter.append("line")
.append("title")
link.selectAll("line")
.filter( function (d) {
return d.type != 'client'
})
.style("stroke", function(d) {
return linkcolor(Math.max.apply(null, d.quality.split(",")))
})
link.selectAll("title")
.text( function (d) {
var s = d.quality
if (d.type)
s += " (" + d.type + ")"
return s
})
link.exit().remove()
var nodes = data.nodes.filter(function (d) {
if (!visible.vpn && d.flags.vpn)
return false
if (!visible.clients && d.flags.client)
return false
if (!d.flags.online)
return false
return true
})
var node = vis.select("g.nodes")
.selectAll("g.node")
.data(nodes,
function(d) {
return d.id
}
)
var nodeEnter = node.enter().append("g")
.attr("id", function (d) {
return d.id
})
.attr("class", "node")
.on("mouseover", fade(.2))
.on("mouseout", fade(1))
.on("click", show_node_info)
.call(force.drag)
nodeEnter.append("ellipse")
.attr("class", function(d) {
var s = []
for (var key in d.flags)
if (d.flags.hasOwnProperty(key) && d.flags[key])
s.push(key)
return s.join(" ")
})
node.selectAll("ellipse")
.attr("rx", function(d) {
if (d.flags.client) return 4
else return Math.max(10, d.name.length * 5)
})
.attr("ry", function(d) {
if (d.flags.client) return 4
else return 10
})
nodeEnter.filter(function(d) {
return !d.flags.client
})
.append("text")
.attr("class", "name")
.attr("text-anchor", "middle")
.attr("y", "4px")
node.selectAll("text.name")
.text(function(d) { return d.name })
nodeEnter.append("title")
node.selectAll("title")
.text(function(d) { return d.macs })
node.selectAll(".uplinks").remove()
if (!visible.vpn) {
var uplink_info = node.filter(function (d) {
return d.vpns > 0
})
.append("g")
.attr("class", "uplinks")
uplink_info.append("path")
.attr("d","m -2.8850049,-13.182327"
+ "c 7.5369165,0.200772 12.1529864,-1.294922 12.3338513,-10.639456"
+ "l 2.2140476,1.018191 -3.3137621,-5.293097 -3.2945999,5.20893 2.4339957,-0.995747"
+ "c -0.4041883,5.76426 -1.1549641,10.561363 -10.3735326,10.701179 z")
uplink_info.append("text")
.attr("text-anchor", "middle")
.attr("y", 3 - 20)
.text(function (d) {return d.vpns})
}
node.exit().remove()
force.nodes(nodes)
.links(links)
.alpha(0.1)
.start()
linkedByIndex = {}
links.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1
})
if (hashstr.length != 0)
show_node(hashstr)
}
function bounding_box(d) {
var c = d.firstChild
var r = {}
switch(c.nodeName) {
case "ellipse":
r.rx = c.rx.animVal.value
r.ry = c.ry.animVal.value
break;
case "circle":
r.rx = r.rz = c.r.animVal.value
break;
default:
r.rx = r.ry = 10
}
return r
}
reload()
var timer = window.setInterval(reload, 30000)
| html/force.js | var style;
function switch_style(s) {
var el = document.getElementsByTagName("link")
for (var i = 0; i < el.length; i++ ) {
if (el[i].getAttribute("rel").indexOf("style") != -1
&& el[i].getAttribute("title")) {
if (el[i].getAttribute("title") == s) {
style_btn.text(s)
el[i].disabled = false
} else
el[i].disabled = true
}
}
}
function getOffset( el ) {
var _x = 0, _y = 0
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft
_y += el.offsetTop - el.scrollTop
el = el.offsetParent
}
return { top: _y, left: _x }
}
var offset = getOffset(document.getElementById('chart'))
var w, h
resize()
window.onresize = resize
function resize() {
var offset = getOffset(document.getElementById('chart'))
w = window.innerWidth - offset.left
h = window.innerHeight - offset.top - 1
d3.select("#chart")
.attr("width", w).attr("height", h)
if (vis)
vis.attr("width", w).attr("height", h)
if (force)
force.size([w, h]).start()
}
function next_style() {
var s;
if (style !== undefined)
s = d3.select("head link[title=" + style + "] + link")
if (s == null || s[0][0] == null)
s = d3.select("head link[title]")
style = s[0][0].getAttribute("title")
switch_style(style)
}
var cp = d3.select("header").append("div")
.attr("id", "controlpanel")
var updated_at = cp.append("p")
cp.append("button")
.attr("class", "btn")
.attr("value", "reload")
.text("Aktualisieren")
.on("click", reload)
var style_btn = cp.append("button")
.attr("class", "btn")
.attr("value", "reload")
.text("Farbwechsler")
.on("click", next_style)
cp.append("button")
.attr("class", "btn")
.attr("value", "reload")
.on("click", pacman)
.append("svg")
.attr("width", 12)
.attr("height", 12)
.append("path")
.attr("d", d3.svg.arc().innerRadius(0)
.outerRadius(5)
.endAngle(-Math.PI/4 + Math.PI/2 + 2*Math.PI)
.startAngle(Math.PI/4 + Math.PI/2))
.attr("fill", "#888")
.attr("transform", "translate(6,7)")
var btns = cp.append("div")
.attr("class", "btn-group")
btns.append("button")
.attr("class", "btn active left")
.attr("value", "clients")
.text("Clients")
.on("click", update_graph)
btns.append("button")
.attr("class", "btn active right")
.attr("value", "vpn")
.text("VPN")
.on("click", update_graph)
var meshinfo = d3.select("sidebar")
.insert("div", ":first-child")
meshinfo.append("h2").text("Mesh")
meshinfo.append("p")
.attr("id", "nodecount")
meshinfo.append("p")
.attr("id", "gatewaycount")
meshinfo.append("p")
.attr("id", "clientcount")
//cp.append("input")
// .on("keyup", function(){show_node(this.value)})
// .on("change", function(){show_node(this.value)})
function show_node(mac) {
d3.selectAll("#chart .node")
.classed("marked", false)
if (mac.length == 0)
return
d3.selectAll("#chart .node")
.each( function(d) {
if (d.id == mac)
d3.select(this)
.classed("marked", true)
})
}
var hashstr = window.location.hash.substring(1)
function isConnected(a, b) {
return linkedByIndex[a.index + "," + b.index] ||
linkedByIndex[b.index + "," + a.index] ||
a.index == b.index
}
function fade(opacity) {
return function(d) {
vis.selectAll("g.node")
.style("stroke-opacity", function(o) {
var connected = isConnected(d, o)
if (connected && opacity != 1)
d3.select(this)
.classed("highlight", true)
else
d3.select(this)
.classed("highlight", false)
thisOpacity = connected?1:opacity
this.setAttribute('fill-opacity', thisOpacity)
return thisOpacity
})
vis.selectAll(".link *")
.style("stroke-opacity", function(o) {
return o.source === d || o.target === d ? 1 : opacity
})
}
}
function show_node_info(d) {
d3.selectAll("#nodeinfo").remove()
nodeinfo = d3.select("#chart")
.append("div")
.attr("id", "nodeinfo")
nodeinfo.append("button")
.attr("class", "close")
.text("x")
.on("click", function(d) {
nodeinfo.remove()
})
nodeinfo.append("h1")
.text(d.name + " / " + d.id)
nodeinfo.append("p")
.append("label")
.text("macs: " + d.macs)
if (d.geo) {
nodeinfo.append("h2").text("Geodaten")
nodeinfo.append("p")
.text(d.geo)
url = GMaps.staticMapURL({
size: [300, 100],
lat: d.geo[0],
lng: d.geo[1],
markers: [
{lat: d.geo[0], lng: d.geo[1]}
]
})
nodeinfo.append("img")
.attr("src", url)
}
}
function update_graph() {
jQuery(this).toggleClass("active")
var value = jQuery(this).val()
visible[value] = jQuery(this).hasClass("active")
update()
}
var vis = d3.select("#chart").append("svg")
.attr("width", w)
.attr("height", h)
vis.append("g").attr("class", "links")
vis.append("g").attr("class", "nodes")
var linkedByIndex
var force = d3.layout.force()
.charge( function (d) {
if (d.flags.client)
return -30
return -200
})
.gravity(0.035)
.friction(0.73)
.theta(0.8)
.size([w, h])
.linkDistance(function (d) {
switch (d.type) {
case "vpn": return 200
case "client": return 20
default: return 70
}
})
.linkStrength(function (d) {
switch (d.type) {
case "vpn": return 0.05
case "client": return 1
default: return 0.8
}
})
force.on("tick", function() {
var size = force.size()
var nodes = force.nodes()
var n = nodes.length
for (i = 0; i < n; i++) {
var o = nodes[i]
if (!o.fixed) {
node = d3.select(document.getElementById(o.id))[0][0]
box = bounding_box(node)
if (o.x < box.rx) o.x = box.rx
if (o.x > size[0] - box.rx) o.x = size[0] - box.rx
if (o.y < box.ry) o.y = box.ry
if (o.y > size[1] - box.ry) o.y = size[1] - box.ry
}
}
var link = vis.selectAll(".link")
link.selectAll("line")
.attr("x1", function(d) { return d.source.x })
.attr("y1", function(d) { return d.source.y })
.attr("x2", function(d) { return d.target.x })
.attr("y2", function(d) { return d.target.y })
vis.selectAll(".node").attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
})
var data
var visible = {clients: true, vpn: true}
function reload() {
d3.json("nodes.json", function(json) {
// update existing nodes with new info
// XXX inefficient data structure
json.nodes.forEach(function(d, i) {
var n
force.nodes().forEach(function(x) {if (x.id == d.id) n = x})
if (n) {
for (var key in d)
if (d.hasOwnProperty(key))
n[key] = d[key]
json.nodes[i] = n
}
})
json.links.forEach(function(d, i) {
var n
force.links().forEach(function(x) {if (x.id == d.id) n = x})
if (n) {
for (var key in d)
if (d.hasOwnProperty(key))
n[key] = d[key]
json.links[i] = n
}
})
// replace indices with real objects
json.links.forEach( function(d) {
if (typeof d.source == "number") d.source = json.nodes[d.source];
if (typeof d.target == "number") d.target = json.nodes[d.target];
})
// count vpn links
json.nodes.forEach(function(d) {
d.vpns = 0
})
json.links.forEach(function(d) {
var node, other
if (d.type == "vpn") {
d.source.vpns++
d.target.vpns++
}
})
data = json
updated_at.text(d3.time.format("%X")(new Date()))
var nNodes = data.nodes.filter(function(d) {
return !d.flags.client
}).length,
nGateways = data.nodes.filter(function(d) {
return d.flags.gateway
}).length,
nClients = data.nodes.filter(function(d) {
return d.flags.client
}).length
d3.select("#nodecount")
.text(nNodes + " Knoten")
d3.select("#gatewaycount")
.text(nGateways + " Gateways")
d3.select("#clientcount")
.text("ungefähr " + (nClients - nNodes) + " Clients")
update()
})
}
var linkcolor = d3.scale.linear()
.domain([1, 1.5, 3])
.range(["#0a3", "orange", "red"]);
function update() {
var links = data.links
.filter(function (d) {
if (!visible.vpn && d.type == "vpn")
return false
if (!visible.clients && (d.source.flags.client || d.target.flags.client))
return false
// hides links to clients
if (!visible.vpn && (d.source.flags.vpn || d.target.flags.vpn))
return false
return true
})
var link = vis.select("g.links")
.selectAll("g.link")
.data(links, function(d) {
return d.id
})
var linkEnter = link.enter().append("g")
.attr("class", function(d) {
return "link " + d.type
})
.on("mouseover", function(d) {
d.source.fixed |= 2
d.target.fixed |= 2
})
.on("mouseout", function(d) {
d.source.fixed &= 1
d.target.fixed &= 1
})
linkEnter.append("line")
.append("title")
link.selectAll("line")
.filter( function (d) {
return d.type != 'client'
})
.style("stroke", function(d) {
return linkcolor(Math.max.apply(null, d.quality.split(",")))
})
link.selectAll("title")
.text( function (d) {
var s = d.quality
if (d.type)
s += " (" + d.type + ")"
return s
})
link.exit().remove()
var nodes = data.nodes.filter(function (d) {
if (!visible.vpn && d.flags.vpn)
return false
if (!visible.clients && d.flags.client)
return false
if (!d.flags.online)
return false
return true
})
var node = vis.select("g.nodes")
.selectAll("g.node")
.data(nodes,
function(d) {
return d.id
}
)
var nodeEnter = node.enter().append("g")
.attr("id", function (d) {
return d.id
})
.attr("class", "node")
.on("mouseover", fade(.2))
.on("mouseout", fade(1))
.on("click", show_node_info)
.call(force.drag)
nodeEnter.append("ellipse")
.attr("class", function(d) {
var s = []
for (var key in d.flags)
if (d.flags.hasOwnProperty(key) && d.flags[key])
s.push(key)
return s.join(" ")
})
node.selectAll("ellipse")
.attr("rx", function(d) {
if (d.flags.client) return 4
else return Math.max(10, d.name.length * 5)
})
.attr("ry", function(d) {
if (d.flags.client) return 4
else return 10
})
nodeEnter.filter(function(d) {
return !d.flags.client
})
.append("text")
.attr("class", "name")
.attr("text-anchor", "middle")
.attr("y", "4px")
node.selectAll("text.name")
.text(function(d) { return d.name })
nodeEnter.append("title")
node.selectAll("title")
.text(function(d) { return d.macs })
node.selectAll(".uplinks").remove()
if (!visible.vpn) {
var uplink_info = node.filter(function (d) {
return d.vpns > 0
})
.append("g")
.attr("class", "uplinks")
uplink_info.append("path")
.attr("d","m -2.8850049,-13.182327"
+ "c 7.5369165,0.200772 12.1529864,-1.294922 12.3338513,-10.639456"
+ "l 2.2140476,1.018191 -3.3137621,-5.293097 -3.2945999,5.20893 2.4339957,-0.995747"
+ "c -0.4041883,5.76426 -1.1549641,10.561363 -10.3735326,10.701179 z")
uplink_info.append("text")
.attr("text-anchor", "middle")
.attr("y", 3 - 20)
.text(function (d) {return d.vpns})
}
node.exit().remove()
force.nodes(nodes)
.links(links)
.alpha(0.1)
.start()
linkedByIndex = {}
links.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1
})
if (hashstr.length != 0)
show_node(hashstr)
}
function bounding_box(d) {
var c = d.firstChild
var r = {}
switch(c.nodeName) {
case "ellipse":
r.rx = c.rx.animVal.value
r.ry = c.ry.animVal.value
break;
case "circle":
r.rx = r.rz = c.r.animVal.value
break;
default:
r.rx = r.ry = 10
}
return r
}
reload()
var timer = window.setInterval(reload, 30000)
| don't count offline nodes
| html/force.js | don't count offline nodes | <ide><path>tml/force.js
<ide> updated_at.text(d3.time.format("%X")(new Date()))
<ide>
<ide> var nNodes = data.nodes.filter(function(d) {
<del> return !d.flags.client
<add> return !d.flags.client && d.flags.online
<ide> }).length,
<ide> nGateways = data.nodes.filter(function(d) {
<del> return d.flags.gateway
<add> return d.flags.gateway && d.flags.online
<ide> }).length,
<ide> nClients = data.nodes.filter(function(d) {
<del> return d.flags.client
<add> return d.flags.client && d.flags.online
<ide> }).length
<ide>
<ide> d3.select("#nodecount") |
|
JavaScript | unlicense | 23f5461f2c29600bd57cfcf7d97db50043a2bf55 | 0 | thisismyrobot/dnstwister,thisismyrobot/dnstwister,thisismyrobot/dnstwister | /* globals fetch, addEventListener, Headers, Response */
// Route: https://dnstwister.report/api/ip2*
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const urlStart = 'https://cloudflare-dns.com/dns-query?type=A&ct=application/dns-json&name='
const jsonHeaders = new Headers([
['Content-Type', 'application/json'],
['Access-Control-Allow-Origin', '*']
])
async function handleRequest (request) {
const parsedUrl = new URL(request.url)
if (!parsedUrl.searchParams.has('pd')) {
return new Response('Missing encoded domain parameter', { status: 403 })
}
let domain = parsedUrl.searchParams.get('pd')
return fetch(urlStart + domain, { cf: { cacheTtl: 86400 } })
.then(function (response) {
if (response.ok) {
return response.json()
}
})
.then(function (data) {
let response = {
ip: false,
error: false
}
if (data.Answer !== undefined && data.Answer.length > 0) {
response.ip = data.Answer.find(function (element) {
return element.type === 1
}).data
}
return new Response(JSON.stringify(response), {
headers: jsonHeaders
})
})
.catch(function () {
let response = {
ip: null,
error: true
}
return new Response(JSON.stringify(response), {
headers: jsonHeaders
})
})
}
| cf-workers/resolve-worker.js | /* globals fetch, addEventListener, Headers, Response */
// Route: https://dnstwister.report/api/ip2*
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const jsonHeaders = new Headers([
['Content-Type', 'application/json'],
['Access-Control-Allow-Origin', '*']
])
async function handleRequest (request) {
const parsedUrl = new URL(request.url)
if (!parsedUrl.searchParams.has('pd')) {
return new Response('Missing encoded domain parameter', { status: 403 })
}
let domain = parsedUrl.searchParams.get('pd')
return fetch('https://dns.google.com/resolve?name=' + domain, { cf: { cacheTtl: 86400 } })
.then(function (response) {
if (response.ok) {
return response.json()
}
})
.then(function (data) {
let response = {
ip: false,
error: false
}
if (data.Answer !== undefined && data.Answer.length > 0) {
response.ip = data.Answer.find(function (element) {
return element.type === 1
}).data
}
return new Response(JSON.stringify(response), {
headers: jsonHeaders
})
})
.catch(function () {
let response = {
ip: null,
error: true
}
return new Response(JSON.stringify(response), {
headers: jsonHeaders
})
})
}
| Switched to CF's DNS :)
| cf-workers/resolve-worker.js | Switched to CF's DNS :) | <ide><path>f-workers/resolve-worker.js
<ide> addEventListener('fetch', event => {
<ide> event.respondWith(handleRequest(event.request))
<ide> })
<add>
<add>const urlStart = 'https://cloudflare-dns.com/dns-query?type=A&ct=application/dns-json&name='
<ide>
<ide> const jsonHeaders = new Headers([
<ide> ['Content-Type', 'application/json'],
<ide>
<ide> let domain = parsedUrl.searchParams.get('pd')
<ide>
<del> return fetch('https://dns.google.com/resolve?name=' + domain, { cf: { cacheTtl: 86400 } })
<add> return fetch(urlStart + domain, { cf: { cacheTtl: 86400 } })
<ide> .then(function (response) {
<ide> if (response.ok) {
<ide> return response.json() |
|
Java | bsd-3-clause | 0a16e2c5afef0ca43f9b438eda80e941e5ba0e23 | 0 | muloem/xins,muloem/xins,muloem/xins | /*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.types;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.xins.common.Log;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.Utils;
import org.xins.logdoc.ExceptionUtils;
/**
* Abstract base class for pattern types. A pattern type only accepts values
* that match a certain regular expression.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 1.0.0
*/
public abstract class PatternType extends Type {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The fully-qualified name of this class.
*/
private static final String CLASSNAME = PatternType.class.getName();
/**
* Perl 5 pattern compiler.
*/
private static final Perl5Compiler PATTERN_COMPILER = new Perl5Compiler();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Creates a new <code>PatternType</code> instance. The name of the type
* needs to be specified. The value class (see
* {@link Type#getValueClass()}) is set to {@link String String.class}.
*
* @param name
* the name of the type, not <code>null</code>.
*
* @param pattern
* the regular expression the values must match, not <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>name == null || pattern == null</code>.
*
* @throws PatternCompileException
* if the specified pattern is considered invalid.
*/
protected PatternType(String name, String pattern)
throws IllegalArgumentException, PatternCompileException {
super(name, String.class);
if (pattern == null) {
throw new IllegalArgumentException("pattern == null");
}
// Compile the regular expression to a Pattern object
try {
synchronized (PATTERN_COMPILER) {
_pattern = PATTERN_COMPILER.compile(pattern,
Perl5Compiler.READ_ONLY_MASK);
}
// Handle pattern compilation error
} catch (MalformedPatternException mpe) {
PatternCompileException e = new PatternCompileException(pattern);
ExceptionUtils.setCause(e, mpe);
throw e;
}
// Store the original pattern string
_patternString = pattern;
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* Pattern string. This is the uncompiled version of {@link #_pattern}.
* This field cannot be <code>null</code>.
*/
private final String _patternString;
/**
* Compiled pattern. This is the compiled version of
* {@link #_patternString}. This field cannot be <code>null</code>.
*/
private final Pattern _pattern;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
protected final boolean isValidValueImpl(String value) {
// Determine if the value matches the pattern
try {
Perl5Matcher patternMatcher = new Perl5Matcher();
return patternMatcher.matches(value, _pattern);
// If the call causes an exception, then log that exception and assume
// the value does not match the pattern
} catch (Throwable exception) {
String thisMethod = "isValidValueImpl(java.lang.String)";
String subjectClass = "org.apache.oro.text.regex.Perl5Matcher";
String subjectMethod = "matches(java.lang.String,"
+ _pattern.getClass().getName()
+ ')';
String detail = "Assuming the value \""
+ value
+ "\" is invalid for the pattern \""
+ _patternString
+ "\".";
Utils.logProgrammingError(CLASSNAME, thisMethod,
subjectClass, subjectMethod,
detail, exception);
return false;
}
}
protected final Object fromStringImpl(String value) {
return value;
}
public final String toString(Object value)
throws IllegalArgumentException, ClassCastException, TypeValueException {
MandatoryArgumentChecker.check("value", value);
String s = (String) value;
if (!isValidValueImpl(s)) {
throw new TypeValueException(this, s);
}
return s;
}
/**
* Returns the pattern.
*
* @return
* the pattern, not <code>null</code>.
*/
public String getPattern() {
return _patternString;
}
}
| src/java-common/org/xins/common/types/PatternType.java | /*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.types;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.xins.common.Log;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.Utils;
import org.xins.logdoc.ExceptionUtils;
/**
* Abstract base class for pattern types. A pattern type only accepts values
* that match a certain regular expression.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 1.0.0
*/
public abstract class PatternType extends Type {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The fully-qualified name of this class.
*/
private static final String CLASSNAME = PatternType.class.getName();
/**
* Perl 5 pattern compiler.
*/
private static final Perl5Compiler PATTERN_COMPILER = new Perl5Compiler();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Creates a new <code>PatternType</code> instance. The name of the type
* needs to be specified. The value class (see
* {@link Type#getValueClass()}) is set to {@link String String.class}.
*
* @param name
* the name of the type, not <code>null</code>.
*
* @param pattern
* the regular expression the values must match, not <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>name == null || pattern == null</code>.
*
* @throws PatternCompileException
* if the specified pattern is considered invalid.
*/
protected PatternType(String name, String pattern)
throws IllegalArgumentException, PatternCompileException {
super(name, String.class);
if (pattern == null) {
throw new IllegalArgumentException("pattern == null");
}
// Compile the regular expression to a Pattern object
try {
synchronized (PATTERN_COMPILER) {
_pattern = PATTERN_COMPILER.compile(pattern,
Perl5Compiler.READ_ONLY_MASK);
}
// Handle pattern compilation error
} catch (MalformedPatternException mpe) {
PatternCompileException e = new PatternCompileException(pattern);
ExceptionUtils.setCause(e, mpe);
throw e;
}
// Store the original pattern string
_patternString = pattern;
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* Pattern string. This is the uncompiled version of {@link #_pattern}.
* This field cannot be <code>null</code>.
*/
private final String _patternString;
/**
* Compiled pattern. This is the compiled version of
* {@link #_patternString}. This field cannot be <code>null</code>.
*/
private final Pattern _pattern;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
protected final boolean isValidValueImpl(String value) {
// Determine if the value matches the pattern
try {
Perl5Matcher patternMatcher = new Perl5Matcher();
return patternMatcher.matches(value, _pattern);
// If the call causes an exception, then log that exception and assume
// the value does not match the pattern
} catch (Throwable exception) {
String thisMethod = "isValidValueImpl(java.lang.String)";
String subjectClass = "org.apache.oro.text.regex.Perl5Matcher";
String subjectMethod = "matches(java.lang.String,"
+ _pattern.getClass().getName()
+ ')';
String detail = "Assuming the value \""
+ value
+ "\" is invalid for the pattern \""
+ _patternString
+ "\".";
Utils.logProgrammingError(exception,
CLASSNAME, thisMethod,
subjectClass, subjectMethod,
detail);
return false;
}
}
protected final Object fromStringImpl(String value) {
return value;
}
public final String toString(Object value)
throws IllegalArgumentException, ClassCastException, TypeValueException {
MandatoryArgumentChecker.check("value", value);
String s = (String) value;
if (!isValidValueImpl(s)) {
throw new TypeValueException(this, s);
}
return s;
}
/**
* Returns the pattern.
*
* @return
* the pattern, not <code>null</code>.
*/
public String getPattern() {
return _patternString;
}
}
| Fixed one syntax error.
| src/java-common/org/xins/common/types/PatternType.java | Fixed one syntax error. | <ide><path>rc/java-common/org/xins/common/types/PatternType.java
<ide> + "\" is invalid for the pattern \""
<ide> + _patternString
<ide> + "\".";
<del> Utils.logProgrammingError(exception,
<del> CLASSNAME, thisMethod,
<add> Utils.logProgrammingError(CLASSNAME, thisMethod,
<ide> subjectClass, subjectMethod,
<del> detail);
<add> detail, exception);
<ide> return false;
<ide> }
<ide> } |
|
Java | apache-2.0 | c4db1f3769d779fc13e242d4497ffc763a8120c5 | 0 | kunickiaj/datacollector,kunickiaj/datacollector,streamsets/datacollector,kunickiaj/datacollector,streamsets/datacollector,streamsets/datacollector,kunickiaj/datacollector,streamsets/datacollector,streamsets/datacollector,kunickiaj/datacollector | /*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.stage.processor.kudulookup;
import com.streamsets.pipeline.api.Stage;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.OnRecordError;
import com.streamsets.pipeline.sdk.ProcessorRunner;
import com.streamsets.pipeline.stage.lib.kudu.KuduFieldMappingConfig;
import com.streamsets.testing.Matchers;
import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.client.AsyncKuduClient;
import org.apache.kudu.client.AsyncKuduSession;
import org.apache.kudu.client.KuduTable;
import org.apache.kudu.client.Operation;
import org.apache.kudu.client.KuduException;
import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertThat;
@RunWith(PowerMockRunner.class)
@PrepareForTest({
KuduLookupProcessor.class,
AsyncKuduClient.class,
KuduTable.class,
AsyncKuduSession.class,
})
@PowerMockIgnore({ "javax.net.ssl.*" })
public class TestKuduLookup {
private static final String KUDU_MASTER = "localhost:7051";
private final String tableName = "test";
@Before
public void setup() throws Exception {
// Sample table and schema
List<ColumnSchema> columns = new ArrayList(2);
columns.add(new ColumnSchema.ColumnSchemaBuilder("key", Type.INT32).key(true).build());
columns.add(new ColumnSchema.ColumnSchemaBuilder("value", Type.STRING).build());
columns.add(new ColumnSchema.ColumnSchemaBuilder("name", Type.STRING).build());
final Schema schema = new Schema(columns);
// Mock KuduTable class
KuduTable table = PowerMockito.mock(KuduTable.class);
PowerMockito.doReturn(schema).when(table).getSchema();
// Mock KuduSession class
PowerMockito.suppress(PowerMockito.method(
AsyncKuduSession.class,
"apply",
Operation.class
));
PowerMockito.suppress(PowerMockito.method(
AsyncKuduSession.class,
"flush"
));
PowerMockito.suppress(PowerMockito.method(
KuduLookupProcessor.class,
"destroy"
));
}
@Test
public void testConnectionFailure() throws Exception{
// Mock connection refused
PowerMockito.stub(
PowerMockito.method(AsyncKuduClient.class, "getTablesList"))
.toThrow(PowerMockito.mock(KuduException.class));
ProcessorRunner runner = getProcessorRunner(tableName);
try {
List<Stage.ConfigIssue> issues = runner.runValidateConfigs();
Assert.assertEquals(1, issues.size());
Stage.ConfigIssue issue = issues.get(0);
assertThat(issue.toString(), Matchers.containsIgnoringCase("KUDU_00"));
} catch (StageException e) {
Assert.fail("should not throw StageException");
}
}
private ProcessorRunner getProcessorRunner(String tableName) {
KuduLookupProcessor processor = getKuduLookupConfig(tableName);
return getProcessorRunner(processor);
}
@NotNull
private KuduLookupProcessor getKuduLookupConfig(String tableName) {
KuduLookupConfig conf = new KuduLookupConfig();
conf.connection.kuduMaster = KUDU_MASTER;
conf.kuduTableTemplate = tableName;
conf.keyColumnMapping = new ArrayList<>();
conf.keyColumnMapping.add(new KuduFieldMappingConfig("/key", "key"));
conf.outputColumnMapping = new ArrayList<>();
conf.outputColumnMapping.add(new KuduOutputColumnMapping("column", "/field", ""));
return new KuduLookupProcessor(conf);
}
private ProcessorRunner getProcessorRunner(KuduLookupProcessor processor) {
return new ProcessorRunner.Builder(KuduLookupDProcessor.class, processor)
.setOnRecordError(OnRecordError.TO_ERROR)
.addOutputLane("lane")
.build();
}
}
| kudu-protolib/src/test/java/com/streamsets/pipeline/stage/processor/kudulookup/TestKuduLookup.java | /*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.stage.processor.kudulookup;
import com.streamsets.pipeline.api.Stage;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.OnRecordError;
import com.streamsets.pipeline.sdk.ProcessorRunner;
import com.streamsets.pipeline.stage.lib.kudu.KuduFieldMappingConfig;
import com.streamsets.testing.Matchers;
import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.client.AsyncKuduClient;
import org.apache.kudu.client.AsyncKuduSession;
import org.apache.kudu.client.KuduTable;
import org.apache.kudu.client.Operation;
import org.apache.kudu.client.KuduException;
import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertThat;
@RunWith(PowerMockRunner.class)
@PrepareForTest({
KuduLookupProcessor.class,
AsyncKuduClient.class,
KuduTable.class,
AsyncKuduSession.class,
})
@PowerMockIgnore({ "javax.net.ssl.*" })
public class TestKuduLookup {
private static final String KUDU_MASTER = "localhost:7051";
private final String tableName = "test";
@Before
public void setup() throws Exception {
// Sample table and schema
List<ColumnSchema> columns = new ArrayList(2);
columns.add(new ColumnSchema.ColumnSchemaBuilder("key", Type.INT32).key(true).build());
columns.add(new ColumnSchema.ColumnSchemaBuilder("value", Type.STRING).build());
columns.add(new ColumnSchema.ColumnSchemaBuilder("name", Type.STRING).build());
final Schema schema = new Schema(columns);
// Mock KuduTable class
KuduTable table = PowerMockito.mock(KuduTable.class);
PowerMockito.doReturn(schema).when(table).getSchema();
// Mock KuduSession class
PowerMockito.suppress(PowerMockito.method(
AsyncKuduSession.class,
"apply",
Operation.class
));
PowerMockito.suppress(PowerMockito.method(
AsyncKuduSession.class,
"flush"
));
PowerMockito.suppress(PowerMockito.method(
KuduLookupProcessor.class,
"destroy"
));
}
@Test
public void testConnectionFailure() throws Exception{
// Mock connection refused
PowerMockito.stub(
PowerMockito.method(AsyncKuduClient.class, "getTablesList"))
.toThrow(PowerMockito.mock(KuduException.class));
ProcessorRunner runner = getProcessorRunner(tableName);
try {
List<Stage.ConfigIssue> issues = runner.runValidateConfigs();
Assert.assertEquals(1, issues.size());
Stage.ConfigIssue issue = issues.get(0);
assertThat(issue.toString(), Matchers.containsIgnoringCase(KuduException.class.getSimpleName()));
} catch (StageException e) {
Assert.fail("should not throw StageException");
}
}
private ProcessorRunner getProcessorRunner(String tableName) {
KuduLookupProcessor processor = getKuduLookupConfig(tableName);
return getProcessorRunner(processor);
}
@NotNull
private KuduLookupProcessor getKuduLookupConfig(String tableName) {
KuduLookupConfig conf = new KuduLookupConfig();
conf.connection.kuduMaster = KUDU_MASTER;
conf.kuduTableTemplate = tableName;
conf.keyColumnMapping = new ArrayList<>();
conf.keyColumnMapping.add(new KuduFieldMappingConfig("/key", "key"));
conf.outputColumnMapping = new ArrayList<>();
conf.outputColumnMapping.add(new KuduOutputColumnMapping("column", "/field", ""));
return new KuduLookupProcessor(conf);
}
private ProcessorRunner getProcessorRunner(KuduLookupProcessor processor) {
return new ProcessorRunner.Builder(KuduLookupDProcessor.class, processor)
.setOnRecordError(OnRecordError.TO_ERROR)
.addOutputLane("lane")
.build();
}
}
| SDC-15658. Fix Kudu Lookup Processor test assertion
Change-Id: Ibf421344342eaf6890fcfa70b1be4776f2bf8ac8
Reviewed-on: https://review.streamsets.net/c/datacollector/+/34431
Reviewed-by: Santhosh Kumar <[email protected]>
| kudu-protolib/src/test/java/com/streamsets/pipeline/stage/processor/kudulookup/TestKuduLookup.java | SDC-15658. Fix Kudu Lookup Processor test assertion | <ide><path>udu-protolib/src/test/java/com/streamsets/pipeline/stage/processor/kudulookup/TestKuduLookup.java
<ide> List<Stage.ConfigIssue> issues = runner.runValidateConfigs();
<ide> Assert.assertEquals(1, issues.size());
<ide> Stage.ConfigIssue issue = issues.get(0);
<del> assertThat(issue.toString(), Matchers.containsIgnoringCase(KuduException.class.getSimpleName()));
<add> assertThat(issue.toString(), Matchers.containsIgnoringCase("KUDU_00"));
<ide> } catch (StageException e) {
<ide> Assert.fail("should not throw StageException");
<ide> } |
|
Java | lgpl-2.1 | 02d5b16de42d7237e780d029a5af1f0618ed8744 | 0 | blue-systems-group/project.maybe.polyglot,xcv58/polyglot,liujed/polyglot-eclipse,xcv58/polyglot,xcv58/polyglot,liujed/polyglot-eclipse,liujed/polyglot-eclipse,xcv58/polyglot,blue-systems-group/project.maybe.polyglot,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,blue-systems-group/project.maybe.polyglot | /*
* Assert.java
*/
package polyglot.util;
/**
* Assert
*
* Overview:
* Assert contains a few methods helpful for implementing assertions in
* Java.
**/
public final class Assert {
/**
* static void check(boolean ok)
*
* Throws an error if not <ok>.
**/
public static void check(boolean ok) {
if (!ok)
throw new AssertionFailedError("Assertion failed");
}
/**
* static void check(String condition, boolean ok)
*
* Asserts that <condition> holds -- in other words, that <ok> is true.
* Throws an error otherwise.
**/
public static void check(String condition, boolean ok) {
if (!ok)
throw new AssertionFailedError("Assertion \"" +
condition + "\" failed.");
}
// This class cannot be instantiated.
private Assert() {}
// The error thrown.
private static class AssertionFailedError extends Error {
public AssertionFailedError() { super(); }
public AssertionFailedError(String s) { super(s); }
}
}
| src/polyglot/util/Assert.java | /*
* Assert.java
*/
package polyglot.util;
/**
* Assert
*
* Overview:
* Assert contains a few methods helpful for implementing assertions in
* Java.
**/
public final class Assert {
/**
* static void assert(boolean ok)
*
* Throws an error if not <ok>.
**/
public static void assert(boolean ok) {
if (!ok)
throw new AssertionFailedError("Assertion failed");
}
/**
* static void assert(String condition, boolean ok)
*
* Asserts that <condition> holds -- in other words, that <ok> is true.
* Throws an error otherwise.
**/
public static void assert(String condition, boolean ok) {
if (!ok)
throw new AssertionFailedError("Assertion \"" +
condition + "\" failed.");
}
// This class cannot be instantiated.
private Assert() {}
// The error thrown.
private static class AssertionFailedError extends Error {
public AssertionFailedError() { super(); }
public AssertionFailedError(String s) { super(s); }
}
}
| Changed Assert.assert to Assert.check to avoid warnings from JDK 1.4
javac.
| src/polyglot/util/Assert.java | Changed Assert.assert to Assert.check to avoid warnings from JDK 1.4 javac. | <ide><path>rc/polyglot/util/Assert.java
<ide> public final class Assert {
<ide>
<ide> /**
<del> * static void assert(boolean ok)
<add> * static void check(boolean ok)
<ide> *
<ide> * Throws an error if not <ok>.
<ide> **/
<del> public static void assert(boolean ok) {
<add> public static void check(boolean ok) {
<ide> if (!ok)
<ide> throw new AssertionFailedError("Assertion failed");
<ide> }
<ide>
<ide> /**
<del> * static void assert(String condition, boolean ok)
<add> * static void check(String condition, boolean ok)
<ide> *
<ide> * Asserts that <condition> holds -- in other words, that <ok> is true.
<ide> * Throws an error otherwise.
<ide> **/
<del> public static void assert(String condition, boolean ok) {
<add> public static void check(String condition, boolean ok) {
<ide> if (!ok)
<ide> throw new AssertionFailedError("Assertion \"" +
<ide> condition + "\" failed."); |
|
JavaScript | mit | 712dd48c1e71f21569dc512f38e193b289937105 | 0 | assemble/assemble,xetryj/assemble,a0000001/test,valentinvieriu/assemble,valentinvieriu/assemble,edrohler/assemble,assemble/assemble,assemble/grunt-assemble,cgvarela/assemble,edrohler/assemble,davidwickman/assemble,avr/assemble,cgvarela/assemble,xetryj/assemble,davidwickman/assemble,assemble/grunt-assemble,makotot/assemble | /*
* Assemble
* http://sellside.github.com/assemelbe
*
* Copyright (c) 2013 Assemble
* MIT License
*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
},
// Release management
release: {
options: {
bump: true,
add: false,
commit: false,
tag: false,
push: false,
pushTags: false,
npm: false
}
},
// Update Version
version: {
check: {
src: ['package.json']
},
release: {
options: {
release: 'patch'
},
src: ['package.json']
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
files: ['Gruntfile.js', 'lib/**/*.js', 'tasks/**/*.js', 'test/**/*.js']
},
// Run tests.
mochaTest: {
files: ['test/**/*.js']
},
mochaTestConfig: {
options: {
reporter: 'nyan'
}
},
concat: {
dist: {
src: ['<banner:meta.banner>', '<file_strip_banner:lib/<%= pkg.name %>.js>'],
dest: 'dist/<%= pkg.name %>.js'
}
},
min: {
dist: {
src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
dest: 'dist/<%= pkg.name %>.min.js'
}
},
uglify: {},
watch: {
all: {
files: ['Gruntfile.js', 'lib/**/*.js', 'tasks/**/*.js', 'test/**/*.js'],
tasks: ['jshint', 'mochaTest'],
options: {
debounceDelay: 250
}
}
}
});
// grunt.loadTasks('./tasks');
grunt.loadNpmTasks('grunt-release');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-mocha-test');
//"grunt-version": "https://github.com/kswedberg/grunt-version/tarball/master"
// issue with putting this in the package.json file is that it updates it's own line since it has version": in it.
grunt.loadNpmTasks('grunt-version');
// Default task.
grunt.registerTask('default', [
'jshint',
'mochaTest',
'watch'
]);
// Tests to be run.
grunt.registerTask('test', [
'jshint',
'mochaTest'
]);
};
| Gruntfile.js | /*
* Assemble
* http://sellside.github.com/assemelbe
*
* Copyright (c) 2013 Assemble
* MIT License
*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
},
release: {
options: {
bump: true,
add: false,
commit: false,
tag: false,
push: false,
pushTags: false,
npm: false
}
},
// Update Version
version: {
check: {
src: ['package.json']
},
release: {
options: {
release: 'patch'
},
src: ['package.json']
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
files: ['Gruntfile.js', 'lib/**/*.js', 'tasks/**/*.js', 'test/**/*.js']
},
// Run tests.
mochaTest: {
files: ['test/**/*.js']
},
mochaTestConfig: {
options: {
reporter: 'nyan'
}
},
concat: {
dist: {
src: ['<banner:meta.banner>', '<file_strip_banner:lib/<%= pkg.name %>.js>'],
dest: 'dist/<%= pkg.name %>.js'
}
},
min: {
dist: {
src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
dest: 'dist/<%= pkg.name %>.min.js'
}
},
uglify: {},
watch: {
all: {
files: ['Gruntfile.js', 'lib/**/*.js', 'tasks/**/*.js', 'test/**/*.js'],
tasks: ['jshint', 'mochaTest'],
options: {
debounceDelay: 250
}
}
}
});
// grunt.loadTasks('./tasks');
grunt.loadNpmTasks('grunt-release');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-mocha-test');
//"grunt-version": "https://github.com/kswedberg/grunt-version/tarball/master"
// issue with putting this in the package.json file is that it updates it's own line since it has version": in it.
grunt.loadNpmTasks('grunt-version');
// Default task.
grunt.registerTask('default', [
'jshint',
'mochaTest',
'watch'
]);
// Tests to be run.
grunt.registerTask('test', [
'jshint',
'mochaTest'
]);
};
| gruntfile code comments
| Gruntfile.js | gruntfile code comments | <ide><path>runtfile.js
<ide> ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
<ide> },
<ide>
<del>
<add> // Release management
<ide> release: {
<ide> options: {
<ide> bump: true, |
|
Java | lgpl-2.1 | a13fe2b1079838f71baf6baa4efec342ca58f759 | 0 | victos/opencms-core,sbonoc/opencms-core,gallardo/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,victos/opencms-core,gallardo/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,victos/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,alkacon/opencms-core,victos/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,alkacon/opencms-core,MenZil/opencms-core,gallardo/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/staticexport/CmsLinkManager.java,v $
* Date : $Date: 2005/04/05 13:29:14 $
* Version: $Revision: 1.45 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2002 - 2005 Alkacon Software (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.staticexport;
import org.opencms.file.CmsObject;
import org.opencms.file.types.CmsResourceTypeImage;
import org.opencms.main.CmsException;
import org.opencms.main.I_CmsConstants;
import org.opencms.main.OpenCms;
import org.opencms.site.CmsSite;
import org.opencms.site.CmsSiteManager;
import org.opencms.site.CmsSiteMatcher;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.I_CmsWpConstants;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
/**
* Does the link replacement for the ≶link> tags.<p>
*
* Since this functionality is closely related to the static export,
* this class resides in the static export package.<p>
*
* @author Alexander Kandzior ([email protected])
*
* @version $Revision: 1.45 $
*/
public class CmsLinkManager {
/** Base URL to calculate absolute links. */
private static URL m_baseUrl;
/**
* Public constructor.<p>
*/
public CmsLinkManager() {
// empty
}
/**
* Static initializer for the base URL.<p>
*/
static {
m_baseUrl = null;
try {
m_baseUrl = new URL("http://127.0.0.1");
} catch (MalformedURLException e) {
// this won't happen
}
}
/**
* Calculates the absolute uri for the "relativeUri" with the given absolute "baseUri" as start. <p>
*
* If "relativeUri" is already absolute, it is returned unchanged.
* This method also returns "relativeUri" unchanged if it is not well-formed.<p>
*
* @param relativeUri the relative uri to calculate an absolute uri for
* @param baseUri the base uri, this must be an absolute uri
* @return an absolute uri calculated from "relativeUri" and "baseUri"
*/
public static String getAbsoluteUri(String relativeUri, String baseUri) {
if ((relativeUri == null) || (relativeUri.length() >= 1 && relativeUri.charAt(0) == '/')) {
// uri is null or already absolute
return relativeUri;
}
try {
URL url = new URL(new URL(m_baseUrl, baseUri), relativeUri);
if (url.getQuery() == null) {
return url.getPath();
} else {
StringBuffer result = new StringBuffer(url.getPath().length() + url.getQuery().length() + 2);
result.append(url.getPath());
result.append('?');
result.append(url.getQuery());
return result.toString();
}
} catch (MalformedURLException e) {
return relativeUri;
}
}
/**
* Calculates a realtive uri from "fromUri" to "toUri",
* both uri's must be absolute.<p>
*
* @param fromUri the uri to start
* @param toUri the uri to calculate a relative path to
* @return a realtive uri from "fromUri" to "toUri"
*/
public static String getRelativeUri(String fromUri, String toUri) {
StringBuffer result = new StringBuffer();
int pos = 0;
while (true) {
int i = fromUri.indexOf('/', pos);
int j = toUri.indexOf('/', pos);
if ((i == -1) || (i != j) || !fromUri.regionMatches(pos, toUri, pos, i - pos)) {
break;
}
pos = i + 1;
}
// count hops up from here to the common ancestor
for (int i = fromUri.indexOf('/', pos); i > 0; i = fromUri.indexOf('/', i + 1)) {
result.append("../");
}
// append path down from common ancestor to there
result.append(toUri.substring(pos));
return result.toString();
}
/**
* Returns the site path for a given uri.<p>
*
* If the uri contains no site information, but starts with the opencms context, the context is removed.<p>
* <code>/opencms/opencms/system/further_path -> /system/further_path</code>
*
* If the uri contains no site information, the path will be prefixed with the current site
* (if mysite is the site currently selected in the workplace or in the request).<p>
* <pre>
* /folder/page.html -> /sites/mysite/folder/page.html
* </pre>
*
* If the path of the uri is relative, i.e. does not start with "/",
* the path will be prefixed with the current site and the given relative path,
* then normalized.
* If no relative path is given, null is returned.
* If the normalized path is outsite a site, null is returned.<p>
* <pre>
* page.html -> /sites/mysite/{relativePath}/page.html
* ../page.html -> /sites/mysite/page.html
* ../../page.html -> null
* </pre>
*
* If the uri contains a scheme/server name that denotes an opencms site,
* it is replaced by the appropriate site path.<p>
* <pre>
* http://www.mysite.de/folder/page.html -> /sites/mysite/folder/page.html
* </pre>
*
* If the uri contains a scheme/server name that does not match with any site,
* or if the uri is opaque or invalid,
* null is returned.<p>
* <pre>
* http://www.elsewhere.com/page.html -> null
* mailto:[email protected] -> null
* </pre>
*
* @param cms the cms object
* @param relativePath path to use as prefix if neccessary
* @param targetUri the target uri
* @return the root path for the target uri or null
*/
public static String getSitePath(CmsObject cms, String relativePath, String targetUri) {
if (cms == null) {
// required by unit test cases
return targetUri;
}
URI uri;
String path;
String fragment;
String query;
String suffix;
// malformed uri
try {
uri = new URI(targetUri);
path = uri.getPath();
fragment = uri.getFragment();
if (fragment != null) {
fragment = "#" + fragment;
} else {
fragment = "";
}
query = uri.getQuery();
if (query != null) {
query = "?" + query;
} else {
query = "";
}
} catch (Exception e) {
OpenCms.getLog(CmsLinkManager.class).warn(e);
return null;
}
// concat fragment and query
suffix = fragment.concat(query);
// opaque URI
if (uri.isOpaque()) {
return null;
}
// absolute URI (i.e. uri has a scheme component like http:// ...)
if (uri.isAbsolute()) {
CmsSiteMatcher matcher = new CmsSiteMatcher(targetUri);
if (OpenCms.getSiteManager().isMatching(matcher)) {
if (path.startsWith(OpenCms.getSystemInfo().getOpenCmsContext())) {
path = path.substring(OpenCms.getSystemInfo().getOpenCmsContext().length());
}
return cms.getRequestContext().addSiteRoot(
OpenCms.getSiteManager().matchSite(matcher).getSiteRoot(),
path + suffix);
} else {
return null;
}
}
// relative URI (i.e. no scheme component, but filename can still start with "/")
String context = OpenCms.getSystemInfo().getOpenCmsContext();
if ((context != null) && path.startsWith(context)) {
// URI is starting with opencms context
String siteRoot = null;
if (relativePath != null) {
siteRoot = CmsSiteManager.getSiteRoot(relativePath);
}
// cut context from path
path = path.substring(context.length());
if (siteRoot != null) {
// special case: relative path contains a site root, i.e. we are in the root site
if (!path.startsWith(siteRoot)) {
// path does not already start with the site root, we have to add this path as site prefix
return cms.getRequestContext().addSiteRoot(siteRoot, path + suffix);
} else {
// since path already contains the site root, we just leave it unchanged
return path + suffix;
}
} else {
// site root is added with standard mechanism
return cms.getRequestContext().addSiteRoot(path + suffix);
}
}
// URI with relative path is relative to the given relativePath if available and in a site,
// otherwise invalid
if (!"".equals(path) && !path.startsWith("/")) {
if (relativePath != null) {
String absolutePath = getAbsoluteUri(path, cms.getRequestContext().addSiteRoot(relativePath));
if (CmsSiteManager.getSiteRoot(absolutePath) != null) {
return absolutePath + suffix;
}
}
return null;
}
// relative uri (= vfs path relative to currently selected site root)
if (!"".equals(path)) {
return cms.getRequestContext().addSiteRoot(path) + suffix;
}
// uri without path (typically local link)
return suffix;
}
/**
* Returns a positive hash code value for the given string.<p>
*
* @param s the string to calculate the hashcode from
* @return a positive hash code value for this string
*/
public int hashCode(String s) {
int h = s.hashCode();
if (h < 0) {
h = -h;
}
return h;
}
/**
* Substitutes the contents of a link by adding the context path and
* servlet name, and in the case of the "online" project also according
* to the configured static export settings.<p>
*
* A server prefix is prepended if
* <ul>
* <li>the link points to another site</li>
* <li>the link is contained in a normal document and the link references a secure document</li>
* <li>the link is contained in a secure document and the link references a normal document</li>
* </ul>
*
* @param cms the cms context
* @param link the link to process (must be a valid link to a VFS resource with optional parameters)
* @param siteRoot the site root of the link
* @return the substituted link
*/
public String substituteLink(CmsObject cms, String link, String siteRoot) {
if (CmsStringUtil.isEmpty(link)) {
// not a valid link parameter, return an empty String
return "";
}
// make sure we have an absolute link
String absoluteLink = CmsLinkManager.getAbsoluteUri(link, cms.getRequestContext().getUri());
String vfsName;
String parameters;
int pos = absoluteLink.indexOf('?');
// check if the link has parameters, if so cut them
if (pos >= 0) {
vfsName = absoluteLink.substring(0, pos);
parameters = absoluteLink.substring(pos);
} else {
vfsName = absoluteLink;
parameters = null;
}
String resultLink = null;
String uriBaseName = null;
boolean useRelativeLinks = false;
// determine the target site of the link
CmsSite targetSite;
if (CmsStringUtil.isNotEmpty(siteRoot)) {
targetSite = CmsSiteManager.getSite(siteRoot);
} else {
targetSite = CmsSiteManager.getCurrentSite(cms);
}
String serverPrefix = "";
// if the link points to another site, there needs to be a server prefix
if (targetSite != CmsSiteManager.getCurrentSite(cms)) {
serverPrefix = targetSite.getUrl();
}
if (cms.getRequestContext().currentProject().isOnlineProject()) {
// check if we need relative links in the exported pages
if (OpenCms.getStaticExportManager().relativLinksInExport()) {
// try to get base uri from cache
uriBaseName = OpenCms.getStaticExportManager().getCachedOnlineLink(
OpenCms.getStaticExportManager().getCacheKey(
cms.getRequestContext().getSiteRoot(),
cms.getRequestContext().getUri()));
if (uriBaseName == null) {
// base not cached, check if we must export it
if (exportRequired(cms, cms.getRequestContext().getUri())) {
// base uri must also be exported
uriBaseName = OpenCms.getStaticExportManager()
.getRfsName(cms, cms.getRequestContext().getUri());
} else {
// base uri dosn't need to be exported
uriBaseName = OpenCms.getStaticExportManager().getVfsPrefix()
+ cms.getRequestContext().getUri();
}
// cache export base uri
OpenCms.getStaticExportManager().cacheOnlineLink(
OpenCms.getStaticExportManager().getCacheKey(
cms.getRequestContext().getSiteRoot(),
cms.getRequestContext().getUri()),
uriBaseName);
}
// use relative links only on pages that get exported
useRelativeLinks = uriBaseName.startsWith(OpenCms.getStaticExportManager().getRfsPrefix());
}
// check if we have the absolute vfs name for the link target cached
resultLink = OpenCms.getStaticExportManager().getCachedOnlineLink(
cms.getRequestContext().getSiteRoot() + ":" + absoluteLink);
if (resultLink == null) {
// didn't find the link in the cache
if (exportRequired(cms, vfsName)) {
// export required, get export name for target link
if (parameters != null) {
// external link with parameters, so get translated rfsName
resultLink = OpenCms.getStaticExportManager().getTranslatedRfsName(cms, vfsName, parameters);
// now set the parameters to null, we do not need them anymore
parameters = null;
} else {
resultLink = OpenCms.getStaticExportManager().getRfsName(cms, vfsName);
}
} else {
// no export required for the target link
resultLink = OpenCms.getStaticExportManager().getVfsPrefix().concat(vfsName);
// add cut off parameters if required
if (parameters != null) {
resultLink = resultLink.concat(parameters);
}
}
// cache the result
OpenCms.getStaticExportManager().cacheOnlineLink(
cms.getRequestContext().getSiteRoot() + ":" + absoluteLink,
resultLink);
}
// read only properties, if the current site and the target site both do have a secure server
if (targetSite.hasSecureServer() || CmsSiteManager.getCurrentSite(cms).hasSecureServer()) {
if (!link.startsWith(I_CmsWpConstants.C_VFS_PATH_SYSTEM)) {
boolean secureLink = false;
boolean secureRequest = false;
int linkType = -1;
try {
// read the secure property of the link and the current document
secureLink = OpenCms.getStaticExportManager().isSecureLink(cms, link, siteRoot);
secureRequest = OpenCms.getStaticExportManager().isSecureLink(
cms,
cms.getRequestContext().getUri(),
null);
linkType = cms.readResource(link).getTypeId();
} catch (CmsException e) {
// there are no access rights on the resource
if (OpenCms.getLog(this).isInfoEnabled()) {
OpenCms.getLog(this).info(e);
}
}
// images are always referenced without a server prefix
if (linkType != CmsResourceTypeImage.getStaticTypeId()) {
// if we are on a normal server, and the requested resource is secure,
// the server name has to be prepended
if (secureLink && !secureRequest) {
serverPrefix = targetSite.getSecureUrl();
} else if (!secureLink && secureRequest) {
serverPrefix = targetSite.getUrl();
}
}
}
}
// make absolute link relative, if relative links in export are required
// and if the link does not point to another server
if (useRelativeLinks && CmsStringUtil.isEmpty(serverPrefix)) {
resultLink = getRelativeUri(uriBaseName, resultLink);
}
} else {
// offline project, no export required
if (OpenCms.getRunLevel() >= OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
// in unit test this code would fail otherwise
resultLink = OpenCms.getStaticExportManager().getVfsPrefix().concat(vfsName);
}
// add cut off parameters and return the result
if (parameters != null) {
resultLink = resultLink.concat(parameters);
}
}
return serverPrefix.concat(resultLink);
}
/**
* Substitutes the contents of a link by adding the context path and
* servlet name, and in the case of the "online" project also according
* to the configured static export settings.<p>
*
* @param cms the cms context
* @param link the link to process (must be a valid link to a VFS resource with optional parameters)
* @return the substituted link
*/
public String substituteLink(CmsObject cms, String link) {
return substituteLink(cms, link, null);
}
/**
* Checks if the export is required for a given vfs resource.<p>
*
* @param cmsParam the current cms context
* @param vfsName the vfs resource name to check
* @return true if export is required for the given vfsName
*/
protected boolean exportRequired(CmsObject cmsParam, String vfsName) {
boolean result = false;
if (OpenCms.getStaticExportManager().isStaticExportEnabled()) {
try {
// static export must always be checked with the export users permissions,
// not the current users permissions
CmsObject cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserExport());
cms.getRequestContext().setSiteRoot(cmsParam.getRequestContext().getSiteRoot());
// let's look up export property in VFS
String exportValue = cms.readPropertyObject(vfsName, I_CmsConstants.C_PROPERTY_EXPORT, true).getValue();
if (exportValue == null) {
// no setting found for "export" property
if (OpenCms.getStaticExportManager().getExportPropertyDefault()) {
// if the default is "true" we always export
result = true;
} else {
// check if the resource is exportable by suffix
result = OpenCms.getStaticExportManager().isSuffixExportable(vfsName);
}
} else {
// "export" value found, if it was "true" we export
result = Boolean.valueOf(exportValue).booleanValue();
}
} catch (Throwable t) {
// no export required (probably security issues, e.g. no access for export user)
}
}
return result;
}
} | src/org/opencms/staticexport/CmsLinkManager.java | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/staticexport/CmsLinkManager.java,v $
* Date : $Date: 2005/03/30 09:49:31 $
* Version: $Revision: 1.44 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2002 - 2005 Alkacon Software (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.staticexport;
import org.opencms.file.CmsObject;
import org.opencms.file.types.CmsResourceTypeImage;
import org.opencms.main.CmsException;
import org.opencms.main.I_CmsConstants;
import org.opencms.main.OpenCms;
import org.opencms.site.CmsSite;
import org.opencms.site.CmsSiteManager;
import org.opencms.site.CmsSiteMatcher;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.I_CmsWpConstants;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
/**
* Does the link replacement for the ≶link> tags.<p>
*
* Since this functionality is closely related to the static export,
* this class resides in the static export package.<p>
*
* @author Alexander Kandzior ([email protected])
*
* @version $Revision: 1.44 $
*/
public class CmsLinkManager {
/** Base URL to calculate absolute links. */
private static URL m_baseUrl;
/**
* Public constructor.<p>
*/
public CmsLinkManager() {
// empty
}
/**
* Static initializer for the base URL.<p>
*/
static {
m_baseUrl = null;
try {
m_baseUrl = new URL("http://127.0.0.1");
} catch (MalformedURLException e) {
// this won't happen
}
}
/**
* Calculates the absolute uri for the "relativeUri" with the given absolute "baseUri" as start. <p>
*
* If "relativeUri" is already absolute, it is returned unchanged.
* This method also returns "relativeUri" unchanged if it is not well-formed.<p>
*
* @param relativeUri the relative uri to calculate an absolute uri for
* @param baseUri the base uri, this must be an absolute uri
* @return an absolute uri calculated from "relativeUri" and "baseUri"
*/
public static String getAbsoluteUri(String relativeUri, String baseUri) {
if ((relativeUri == null) || (relativeUri.length() >= 1 && relativeUri.charAt(0) == '/')) {
// uri is null or already absolute
return relativeUri;
}
try {
URL url = new URL(new URL(m_baseUrl, baseUri), relativeUri);
if (url.getQuery() == null) {
return url.getPath();
} else {
StringBuffer result = new StringBuffer(url.getPath().length() + url.getQuery().length() + 2);
result.append(url.getPath());
result.append('?');
result.append(url.getQuery());
return result.toString();
}
} catch (MalformedURLException e) {
return relativeUri;
}
}
/**
* Calculates a realtive uri from "fromUri" to "toUri",
* both uri's must be absolute.<p>
*
* @param fromUri the uri to start
* @param toUri the uri to calculate a relative path to
* @return a realtive uri from "fromUri" to "toUri"
*/
public static String getRelativeUri(String fromUri, String toUri) {
StringBuffer result = new StringBuffer();
int pos = 0;
while (true) {
int i = fromUri.indexOf('/', pos);
int j = toUri.indexOf('/', pos);
if ((i == -1) || (i != j) || !fromUri.regionMatches(pos, toUri, pos, i - pos)) {
break;
}
pos = i + 1;
}
// count hops up from here to the common ancestor
for (int i = fromUri.indexOf('/', pos); i > 0; i = fromUri.indexOf('/', i + 1)) {
result.append("../");
}
// append path down from common ancestor to there
result.append(toUri.substring(pos));
return result.toString();
}
/**
* Returns the site path for a given uri.<p>
*
* If the uri contains no site information, but starts with the opencms context, the context is removed.<p>
* <code>/opencms/opencms/system/further_path -> /system/further_path</code>
*
* If the uri contains no site information, the path will be prefixed with the current site
* (if mysite is the site currently selected in the workplace or in the request).<p>
* <pre>
* /folder/page.html -> /sites/mysite/folder/page.html
* </pre>
*
* If the path of the uri is relative, i.e. does not start with "/",
* the path will be prefixed with the current site and the given relative path,
* then normalized.
* If no relative path is given, null is returned.
* If the normalized path is outsite a site, null is returned.<p>
* <pre>
* page.html -> /sites/mysite/{relativePath}/page.html
* ../page.html -> /sites/mysite/page.html
* ../../page.html -> null
* </pre>
*
* If the uri contains a scheme/server name that denotes an opencms site,
* it is replaced by the appropriate site path.<p>
* <pre>
* http://www.mysite.de/folder/page.html -> /sites/mysite/folder/page.html
* </pre>
*
* If the uri contains a scheme/server name that does not match with any site,
* or if the uri is opaque or invalid,
* null is returned.<p>
* <pre>
* http://www.elsewhere.com/page.html -> null
* mailto:[email protected] -> null
* </pre>
*
* @param cms the cms object
* @param relativePath path to use as prefix if neccessary
* @param targetUri the target uri
* @return the root path for the target uri or null
*/
public static String getSitePath(CmsObject cms, String relativePath, String targetUri) {
if (cms == null) {
// required by unit test cases
return targetUri;
}
URI uri;
String path;
String fragment;
String query;
String suffix;
// malformed uri
try {
uri = new URI(targetUri);
path = uri.getPath();
fragment = uri.getFragment();
if (fragment != null) {
fragment = "#" + fragment;
} else {
fragment = "";
}
query = uri.getQuery();
if (query != null) {
query = "?" + query;
} else {
query = "";
}
} catch (Exception e) {
OpenCms.getLog(CmsLinkManager.class).warn(e);
return null;
}
// concat fragment and query
suffix = fragment.concat(query);
// opaque URI
if (uri.isOpaque()) {
return null;
}
// absolute URI (i.e. uri has a scheme component like http:// ...)
if (uri.isAbsolute()) {
CmsSiteMatcher matcher = new CmsSiteMatcher(targetUri);
if (OpenCms.getSiteManager().isMatching(matcher)) {
if (path.startsWith(OpenCms.getSystemInfo().getOpenCmsContext())) {
path = path.substring(OpenCms.getSystemInfo().getOpenCmsContext().length());
}
return cms.getRequestContext().addSiteRoot(
OpenCms.getSiteManager().matchSite(matcher).getSiteRoot(),
path + suffix);
} else {
return null;
}
}
// relative URI (i.e. no scheme component, but filename can still start with "/")
String context = OpenCms.getSystemInfo().getOpenCmsContext();
if ((context != null) && path.startsWith(context)) {
// URI is starting with opencms context
String siteRoot = null;
if (relativePath != null) {
siteRoot = CmsSiteManager.getSiteRoot(relativePath);
}
// cut context from path
path = path.substring(context.length());
if (siteRoot != null) {
// special case: relative path contains a site root, i.e. we are in the root site
if (!path.startsWith(siteRoot)) {
// path does not already start with the site root, we have to add this path as site prefix
return cms.getRequestContext().addSiteRoot(siteRoot, path + suffix);
} else {
// since path already contains the site root, we just leave it unchanged
return path + suffix;
}
} else {
// site root is added with standard mechanism
return cms.getRequestContext().addSiteRoot(path + suffix);
}
}
// URI with relative path is relative to the given relativePath if available and in a site,
// otherwise invalid
if (!"".equals(path) && !path.startsWith("/")) {
if (relativePath != null) {
String absolutePath = getAbsoluteUri(path, cms.getRequestContext().addSiteRoot(relativePath));
if (CmsSiteManager.getSiteRoot(absolutePath) != null) {
return absolutePath + suffix;
}
}
return null;
}
// relative uri (= vfs path relative to currently selected site root)
if (!"".equals(path)) {
return cms.getRequestContext().addSiteRoot(path) + suffix;
}
// uri without path (typically local link)
return suffix;
}
/**
* Returns a positive hash code value for the given string.<p>
*
* @param s the string to calculate the hashcode from
* @return a positive hash code value for this string
*/
public int hashCode(String s) {
int h = s.hashCode();
if (h < 0) {
h = -h;
}
return h;
}
/**
* Substitutes the contents of a link by adding the context path and
* servlet name, and in the case of the "online" project also according
* to the configured static export settings.<p>
*
* A server prefix is prepended if
* <ul>
* <li>the link points to another site</li>
* <li>the link is contained in a normal document and the link references a secure document</li>
* <li>the link is contained in a secure document and the link references a normal document</li>
* </ul>
*
* @param cms the cms context
* @param link the link to process (must be a valid link to a VFS resource with optional parameters)
* @param siteRoot the site root of the link
* @return the substituted link
*/
public String substituteLink(CmsObject cms, String link, String siteRoot) {
if (CmsStringUtil.isEmpty(link)) {
// not a valid link parameter, return an empty String
return "";
}
// make sure we have an absolute link
String absoluteLink = CmsLinkManager.getAbsoluteUri(link, cms.getRequestContext().getUri());
String vfsName;
String parameters;
int pos = absoluteLink.indexOf('?');
// check if the link has parameters, if so cut them
if (pos >= 0) {
vfsName = absoluteLink.substring(0, pos);
parameters = absoluteLink.substring(pos);
} else {
vfsName = absoluteLink;
parameters = null;
}
String resultLink = null;
String uriBaseName = null;
boolean useRelativeLinks = false;
// determine the target site of the link
CmsSite targetSite;
if (CmsStringUtil.isNotEmpty(siteRoot)) {
targetSite = CmsSiteManager.getSite(siteRoot);
} else {
targetSite = CmsSiteManager.getCurrentSite(cms);
}
String serverPrefix = "";
// if the link points to another site, there needs to be a server prefix
if (targetSite != CmsSiteManager.getCurrentSite(cms)) {
serverPrefix = targetSite.getUrl();
}
if (cms.getRequestContext().currentProject().isOnlineProject()) {
// check if we need relative links in the exported pages
if (OpenCms.getStaticExportManager().relativLinksInExport()) {
// try to get base uri from cache
uriBaseName = OpenCms.getStaticExportManager().getCachedOnlineLink(
OpenCms.getStaticExportManager().getCacheKey(
cms.getRequestContext().getSiteRoot(),
cms.getRequestContext().getUri()));
if (uriBaseName == null) {
// base not cached, check if we must export it
if (exportRequired(cms, cms.getRequestContext().getUri())) {
// base uri must also be exported
uriBaseName = OpenCms.getStaticExportManager()
.getRfsName(cms, cms.getRequestContext().getUri());
} else {
// base uri dosn't need to be exported
uriBaseName = OpenCms.getStaticExportManager().getVfsPrefix()
+ cms.getRequestContext().getUri();
}
// cache export base uri
OpenCms.getStaticExportManager().cacheOnlineLink(
OpenCms.getStaticExportManager().getCacheKey(
cms.getRequestContext().getSiteRoot(),
cms.getRequestContext().getUri()),
uriBaseName);
}
// use relative links only on pages that get exported
useRelativeLinks = uriBaseName.startsWith(OpenCms.getStaticExportManager().getRfsPrefix());
}
// check if we have the absolute vfs name for the link target cached
resultLink = OpenCms.getStaticExportManager().getCachedOnlineLink(
cms.getRequestContext().getSiteRoot() + ":" + absoluteLink);
if (resultLink == null) {
// didn't find the link in the cache
if (exportRequired(cms, vfsName)) {
// export required, get export name for target link
if (parameters != null) {
// external link with parameters, so get translated rfsName
resultLink = OpenCms.getStaticExportManager().getTranslatedRfsName(cms, vfsName, parameters);
// now set the parameters to null, we do not need them anymore
parameters = null;
} else {
resultLink = OpenCms.getStaticExportManager().getRfsName(cms, vfsName);
}
} else {
// no export required for the target link
resultLink = OpenCms.getStaticExportManager().getVfsPrefix().concat(vfsName);
// add cut off parameters if required
if (parameters != null) {
resultLink = resultLink.concat(parameters);
}
}
// cache the result
OpenCms.getStaticExportManager().cacheOnlineLink(
cms.getRequestContext().getSiteRoot() + ":" + absoluteLink,
resultLink);
}
if (useRelativeLinks) {
// we want relative links in export, so make the absolute link relative
resultLink = getRelativeUri(uriBaseName, resultLink);
}
// read only properties, if the current site and the target site both do have a secure server
if (targetSite.hasSecureServer() || CmsSiteManager.getCurrentSite(cms).hasSecureServer()) {
if (!link.startsWith(I_CmsWpConstants.C_VFS_PATH_SYSTEM)) {
boolean secureLink = false;
boolean secureRequest = false;
int linkType = -1;
try {
// read the secure property of the link and the current document
secureLink = OpenCms.getStaticExportManager().isSecureLink(cms, link, siteRoot);
secureRequest = OpenCms.getStaticExportManager().isSecureLink(
cms,
cms.getRequestContext().getUri(),
null);
linkType = cms.readResource(link).getTypeId();
} catch (CmsException e) {
// there are no access rights on the resource
if (OpenCms.getLog(this).isInfoEnabled()) {
OpenCms.getLog(this).info(e);
}
}
// images are always referenced without a server prefix
if (linkType != CmsResourceTypeImage.getStaticTypeId()) {
// if we are on a normal server, and the requested resource is secure,
// the server name has to be prepended
if (secureLink && !secureRequest) {
serverPrefix = targetSite.getSecureUrl();
} else if (!secureLink && secureRequest) {
serverPrefix = targetSite.getUrl();
}
}
}
}
} else {
// offline project, no export required
if (OpenCms.getRunLevel() >= OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
// in unit test this code would fail otherwise
resultLink = OpenCms.getStaticExportManager().getVfsPrefix().concat(vfsName);
}
// add cut off parameters and return the result
if (parameters != null) {
resultLink = resultLink.concat(parameters);
}
}
return serverPrefix.concat(resultLink);
}
/**
* Substitutes the contents of a link by adding the context path and
* servlet name, and in the case of the "online" project also according
* to the configured static export settings.<p>
*
* @param cms the cms context
* @param link the link to process (must be a valid link to a VFS resource with optional parameters)
* @return the substituted link
*/
public String substituteLink(CmsObject cms, String link) {
return substituteLink(cms, link, null);
}
/**
* Checks if the export is required for a given vfs resource.<p>
*
* @param cmsParam the current cms context
* @param vfsName the vfs resource name to check
* @return true if export is required for the given vfsName
*/
protected boolean exportRequired(CmsObject cmsParam, String vfsName) {
boolean result = false;
if (OpenCms.getStaticExportManager().isStaticExportEnabled()) {
try {
// static export must always be checked with the export users permissions,
// not the current users permissions
CmsObject cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserExport());
cms.getRequestContext().setSiteRoot(cmsParam.getRequestContext().getSiteRoot());
// let's look up export property in VFS
String exportValue = cms.readPropertyObject(vfsName, I_CmsConstants.C_PROPERTY_EXPORT, true).getValue();
if (exportValue == null) {
// no setting found for "export" property
if (OpenCms.getStaticExportManager().getExportPropertyDefault()) {
// if the default is "true" we always export
result = true;
} else {
// check if the resource is exportable by suffix
result = OpenCms.getStaticExportManager().isSuffixExportable(vfsName);
}
} else {
// "export" value found, if it was "true" we export
result = Boolean.valueOf(exportValue).booleanValue();
}
} catch (Throwable t) {
// no export required (probably security issues, e.g. no access for export user)
}
}
return result;
}
} | Fixed the issue that relative links were not processed correctly
| src/org/opencms/staticexport/CmsLinkManager.java | Fixed the issue that relative links were not processed correctly | <ide><path>rc/org/opencms/staticexport/CmsLinkManager.java
<ide> /*
<ide> * File : $Source: /alkacon/cvs/opencms/src/org/opencms/staticexport/CmsLinkManager.java,v $
<del> * Date : $Date: 2005/03/30 09:49:31 $
<del> * Version: $Revision: 1.44 $
<add> * Date : $Date: 2005/04/05 13:29:14 $
<add> * Version: $Revision: 1.45 $
<ide> *
<ide> * This library is part of OpenCms -
<ide> * the Open Source Content Mananagement System
<ide> *
<ide> * @author Alexander Kandzior ([email protected])
<ide> *
<del> * @version $Revision: 1.44 $
<add> * @version $Revision: 1.45 $
<ide> */
<ide> public class CmsLinkManager {
<ide>
<ide> resultLink);
<ide> }
<ide>
<del> if (useRelativeLinks) {
<del> // we want relative links in export, so make the absolute link relative
<del> resultLink = getRelativeUri(uriBaseName, resultLink);
<del> }
<ide> // read only properties, if the current site and the target site both do have a secure server
<ide> if (targetSite.hasSecureServer() || CmsSiteManager.getCurrentSite(cms).hasSecureServer()) {
<ide> if (!link.startsWith(I_CmsWpConstants.C_VFS_PATH_SYSTEM)) {
<ide> }
<ide> }
<ide> }
<add> }
<add> // make absolute link relative, if relative links in export are required
<add> // and if the link does not point to another server
<add> if (useRelativeLinks && CmsStringUtil.isEmpty(serverPrefix)) {
<add> resultLink = getRelativeUri(uriBaseName, resultLink);
<ide> }
<ide>
<ide> } else { |
|
JavaScript | mit | 602e1117bf3172654e00571614dbde2d169f9b61 | 0 | calvinmetcalf/leaflet-fractal,calvinmetcalf/leaflet-fractal | //fork of original by Alexander Parshin (https://github.com/aparshin), submited with his permision
var colors,fractalFunctions,workerFunc, fractalModule;
if(typeof document === "undefined"){
colors=new Uint32Array([4281282495,4281283263,4281283775,4281284287,4281285055,4281285567,4281286335,4281286847,4281287359,4281288127,4281288639,4281289407,4281289919,4281290431,4281291199,4281291711,4281292479,4281292991,4281293503,4281294271,4281294783,4281295551,4281296063,4281296575,4281297343,4281297855,4281298367,4281299135,4281299647,4281300415,4281300927,4281301439,4281302207,4281302719,4281303487,4281303999,4281304511,4281305279,4281305791,4281306559,4281307071,4281307583,4281308351,4281308863,4281309631,4281310143,4281310655,4281311423,4281311935,4281312447,4281313215,4281313727,4281314495,4281315007,4281315519,4281316287,4281316799,4281317567,4281318079,4281318591,4281319359,4281319356,4281319354,4281319352,4281319349,4281319347,4281319344,4281319342,4281319340,4281319337,4281319335,4281319332,4281319330,4281319328,4281319325,4281319323,4281319321,4281319318,4281319316,4281319313,4281319311,4281319309,4281319306,4281319304,4281319301,4281319299,4281319297,4281319294,4281319292,4281319289,4281319287,4281319285,4281319282,4281319280,4281319277,4281319275,4281319273,4281319270,4281319268,4281319266,4281319263,4281319261,4281319258,4281319256,4281319254,4281319251,4281319249,4281319246,4281319244,4281319242,4281319239,4281319237,4281319234,4281319232,4281319230,4281319227,4281319225,4281319222,4281319220,4281319218,4281319215,4281515823,4281646895,4281777967,4281974575,4282105647,4282302255,4282433327,4282564399,4282761007,4282892079,4283088687,4283219759,4283350831,4283547439,4283678511,4283875119,4284006191,4284137263,4284333871,4284464943,4284661551,4284792623,4284923695,4285120303,4285251375,4285382447,4285579055,4285710127,4285906735,4286037807,4286168879,4286365487,4286496559,4286693167,4286824239,4286955311,4287151919,4287282991,4287479599,4287610671,4287741743,4287938351,4288069423,4288266031,4288397103,4288528175,4288724783,4288855855,4288986927,4289183535,4289314607,4289511215,4289642287,4289773359,4289969967,4290101039,4290297647,4290428719,4290559791,4290756399,4290755631,4290755119,4290754607,4290753839,4290753327,4290752559,4290752047,4290751535,4290750767,4290750255,4290749487,4290748975,4290748463,4290747695,4290747183,4290746671,4290745903,4290745391,4290744623,4290744111,4290743599,4290742831,4290742319,4290741551,4290741039,4290740527,4290739759,4290739247,4290738479,4290737967,4290737455,4290736687,4290736175,4290735407,4290734895,4290734383,4290733615,4290733103,4290732591,4290731823,4290731311,4290730543,4290730031,4290729519,4290728751,4290728239,4290727471,4290726959,4290726447,4290725679,4290725167,4290724399,4290723887,4290723375,4290722607,4290722095,4290721327,4290720815,4290720303,4290719535,4290719538,4290719540,4290719542,4290719545,4290719547,4290719550,4290719552,4290719554,4290719557,4290719559,4290719562,4290719564,4290719566,4290719569,4290719571,4290719574,4290719576,4290719578,4290719581,4290719583,4290719586,4290719588,4290719590,4290719593,4290719595,4290719597,4290719600,4290719602,4290719605,4290719607,4290719609,4290719612,4290719614,4290719617,4290719619,4290719621,4290719624,4290719626,4290719629,4290719631,4290719633,4290719636,4290719638,4290719641,4290719643,4290719645,4290719648,4290719650,4290719652,4290719655,4290719657,4290719660,4290719662,4290719664,4290719667,4290719669,4290719672,4290719674,4290719676,4290719679,4290523071,4290391999,4290260927,4290064319,4289933247,4289736639,4289605567,4289474495,4289277887,4289146815,4288950207,4288819135,4288688063,4288491455,4288360383,4288229311,4288032703,4287901631,4287705023,4287573951,4287442879,4287246271,4287115199,4286918591,4286787519,4286656447,4286459839,4286328767,4286132159,4286001087,4285870015,4285673407,4285542335,4285345727,4285214655,4285083583,4284886975,4284755903,4284624831,4284428223,4284297151,4284100543,4283969471,4283838399,4283641791,4283510719,4283314111,4283183039,4283051967,4282855359,4282724287,4282527679,4282396607,4282265535,4282068927,4281937855,4281741247,4281610175,4281479103,4290719679]);
//functions return number from 0 to (maxIter-1)
fractalModule =function(stdlib){
"use asm";
var pow = stdlib.Math.pow;
var abs = stdlib.Math.abs;
var atan2 = stdlib.Math.atan2;
var cos = stdlib.Math.cos;
var sin = stdlib.Math.sin;
function mandlebrot(cx, cy, maxIter) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn = +( pow(x,2) - pow(y,2) + cx);
y = +((x*y)*2 + cy);
x = +xn;
iter=(iter+1)|0;
}
return iter|0;
}
function burningShip(cx, cy, maxIter) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn = pow(x,2) - pow(y,2) - cx;
y = abs(x*y)*2 + cy;
x = xn;
iter=(iter+1)|0;
}
return iter|0;
}
function multibrot(cx, cy, maxIter, cr) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
cr = cr|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
var n1 = +0;
var n2 = +0;
var n3 = +(pow(x,2)+pow(y,2));
while (+n3 < 4 && (iter|0) < (maxIter|0)) {
if(!n3){
x=+cx;
y=+cy;
n3 = +(pow(x,2)+pow(y,2));
continue;
}
n1=pow(n3,(cr>>1));
n2=cr*atan2(y,x);
xn=n1*cos(n2) + cx;
y=n1*sin(n2) + cy;
x = xn;
n3=(pow(x,2)+pow(y,2));
iter=(iter+1)|0;
}
return iter|0;
}
function multibrot3(cx, cy, maxIter) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn=pow(x,3)-3*x*pow(y,2) + cx;
y=3*pow(x,2)*y-pow(y,3) + cy;
x = xn;
iter=(iter+1)|0;
}
return iter|0;
}
function multibrot5(cx, cy, maxIter) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn=pow(x,5)-(10*pow(x,3)*pow(y,2))+(5*x*pow(y,4)) + cx;
y=(5*pow(x,4)*y)-(10*pow(x,2)*pow(y,3))+pow(y,5) + cy;
x = xn;
iter=(iter+1)|0;
}
return iter|0;
}
function tricorn(cx, cy, maxIter) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn = pow(x,2) - pow(y,2) - cx;
y =(x+x)*(-y) + cy;
x = xn;
iter=(iter+1)|0;
}
return iter|0;
}
function julia(cx, cy, maxIter, cr, ci) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
cr = +cr;
ci = +ci;
var iter=0|0;
var xn= +0;
var x = +cx;
var y = +cy;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn = pow(x,2) - pow(y,2) + cr;
y = (x*y)*2 + ci;
x = xn;
iter=(iter+1)|0;
}
return iter|0;
}
return {
mandlebrot: mandlebrot,
burningShip: burningShip,
multibrot: multibrot,
multibrot3: multibrot3,
multibrot5: multibrot5,
tricorn: tricorn,
julia: julia
};
};
fractalFunctions=fractalModule(self);
workerFunc = function(data,cb) {
var scale = Math.pow(2, data.z - 1);
var x0 = data.x / scale - 1;
var y0 = data.y / scale - 1;
var d = 1/(scale<<8);
var pixels = new Array(65536);
var MAX_ITER=data.maxIter;
var c,cx,cy,iter,i=0,px,py,a1,a2,a3,a4;
while (i < 65536) {
px = i%256;
py = (i-px)>>8;
cx = x0 + px*d;
cy = y0 + py*d;
iter = fractalFunctions[data.type](cx, cy, MAX_ITER, data.cr, data.ci);
c = ~~((iter/MAX_ITER)*360);
pixels[i++] = colors[c];
pixels[i++] = colors[c];
}
i=1;
while (i < 65536) {
px = i%256;
py = (i-px)>>8;
cx = x0 + px*d;
cy = y0 + py*d;
if(!px||!py||!px%255||py%255){
iter = fractalFunctions[data.type](cx, cy, MAX_ITER, data.cr, data.ci);
c = ~~((iter/MAX_ITER)*360);
pixels[i++] = colors[c];
}
else{
a1=pixels[i+1];
a2=pixels[i-1];
a3=pixels[i+256];
a4=pixels[i-256];
if(a1===a2&&a2===a3&&a3===a4){
i++;
}else{
iter = fractalFunctions[data.type](cx, cy, MAX_ITER, data.cr, data.ci);
c = ~~((iter/MAX_ITER)*360);
pixels[i++] = colors[c];
}
}
i++;
}
var array = new Uint32Array(pixels);
data.pixels = array.buffer;
cb(data,[data.pixels]);
};
self.onmessage=function(e){
workerFunc(e.data,function (a,b){
self.postMessage(a,b);
});
};
}else{
L.TileLayer.FractalLayer = L.TileLayer.Canvas.extend({
options: {
async: true,
maxZoom:23,
continuousWorld:true
},
initialize: function (numWorkers,fractalType,maxIter,cr,ci) {
this.fractalType = fractalType || "mandlebrot";
this.numWorkers = numWorkers;
this._workers = new Array(this.numWorkers);
this.messages={};
this.queue={total: numWorkers};
this.cr = cr || -0.74543;
this.ci = ci || 0.11301;
this.maxIter = maxIter || 500;
var scripts = document.getElementsByTagName("script");
var len = scripts.length;
var i = 0;
while(i<len){
if(/FractalLayer\.js/.test(scripts[i].src)){
this.workerPath=scripts[i].src;
break;
}
i++;
}
},
onAdd: function(map) {
var _this = this;
var i = 0;
var next;
this.queue.free = [];
this.queue.len =0;
this.queue.tiles = [];
while(i<this.numWorkers){
this.queue.free.push(i);
this._workers[i]=new Worker(this.workerPath);
this._workers[i].onmessage=function(e) {
var canvas;
if(_this.queue.len) {
_this.queue.len--;
next = _this.queue.tiles.shift();
_this._renderTile(next[0],next[1],e.data.workerID);
} else {
_this.queue.free.push(e.data.workerID);
}
if (e.data.tileID in _this.messages) {
canvas = _this.messages[e.data.tileID];
} else {
return;
}
var array=new Uint8Array(e.data.pixels);
var ctx = canvas.getContext('2d');
var imagedata = ctx.getImageData(0, 0, 256, 256);
imagedata.data.set(array);
ctx.putImageData(imagedata, 0, 0);
_this.tileDrawn(canvas);
};
i++;
}
this.on("tileunload", function(e) {
if(e.tile._tileIndex){
var pos = e.tile._tileIndex,
tileID = [pos.x, pos.y, pos.z].join(':');
if(tileID in _this.messages){
delete _this.messages[tileID];
}
}
});
map.on("zoomstart",function() {
this.queue.len = 0;
this.queue.tiles = [];
}, this);
return L.TileLayer.Canvas.prototype.onAdd.call(this,map);
},
onRemove:function(map){
this.messages={};
var len = this._workers.length;
var i =0;
while(i<len){
this._workers[i].terminate();
i++;
}
return L.TileLayer.Canvas.prototype.onRemove.call(this,map);
},
drawTile: function (canvas, tilePoint) {
if(!this.queue.free.length){
this.queue.tiles.push([canvas,tilePoint]);
this.queue.len++;
}else{
this._renderTile(canvas, tilePoint,this.queue.free.pop());
}
},
_renderTile: function (canvas, tilePoint,workerID) {
var z = this._map.getZoom();
canvas._tileIndex = {x: tilePoint.x, y: tilePoint.y, z: z};
var tileID=tilePoint.x+":"+tilePoint.y+":"+z;
this.messages[tileID]=canvas;
this._workers[workerID].postMessage({
x: tilePoint.x,
y:tilePoint.y,
z: z,
tileID: tileID,
workerID: workerID,
cr: this.cr,
ci: this.ci,
maxIter: this.maxIter,
type: this.fractalType
});
}
});
L.tileLayer.fractalLayer = function(numWorkers,t,mi,cr,ci){
return new L.TileLayer.FractalLayer(numWorkers,t,mi,cr,ci);
}} | FractalLayer.js | //fork of original by Alexander Parshin (https://github.com/aparshin), submited with his permision
var colors,fractalFunctions,workerFunc, fractalModule;
if(typeof document === "undefined"){
colors=new Uint32Array([4281282495,4281283263,4281283775,4281284287,4281285055,4281285567,4281286335,4281286847,4281287359,4281288127,4281288639,4281289407,4281289919,4281290431,4281291199,4281291711,4281292479,4281292991,4281293503,4281294271,4281294783,4281295551,4281296063,4281296575,4281297343,4281297855,4281298367,4281299135,4281299647,4281300415,4281300927,4281301439,4281302207,4281302719,4281303487,4281303999,4281304511,4281305279,4281305791,4281306559,4281307071,4281307583,4281308351,4281308863,4281309631,4281310143,4281310655,4281311423,4281311935,4281312447,4281313215,4281313727,4281314495,4281315007,4281315519,4281316287,4281316799,4281317567,4281318079,4281318591,4281319359,4281319356,4281319354,4281319352,4281319349,4281319347,4281319344,4281319342,4281319340,4281319337,4281319335,4281319332,4281319330,4281319328,4281319325,4281319323,4281319321,4281319318,4281319316,4281319313,4281319311,4281319309,4281319306,4281319304,4281319301,4281319299,4281319297,4281319294,4281319292,4281319289,4281319287,4281319285,4281319282,4281319280,4281319277,4281319275,4281319273,4281319270,4281319268,4281319266,4281319263,4281319261,4281319258,4281319256,4281319254,4281319251,4281319249,4281319246,4281319244,4281319242,4281319239,4281319237,4281319234,4281319232,4281319230,4281319227,4281319225,4281319222,4281319220,4281319218,4281319215,4281515823,4281646895,4281777967,4281974575,4282105647,4282302255,4282433327,4282564399,4282761007,4282892079,4283088687,4283219759,4283350831,4283547439,4283678511,4283875119,4284006191,4284137263,4284333871,4284464943,4284661551,4284792623,4284923695,4285120303,4285251375,4285382447,4285579055,4285710127,4285906735,4286037807,4286168879,4286365487,4286496559,4286693167,4286824239,4286955311,4287151919,4287282991,4287479599,4287610671,4287741743,4287938351,4288069423,4288266031,4288397103,4288528175,4288724783,4288855855,4288986927,4289183535,4289314607,4289511215,4289642287,4289773359,4289969967,4290101039,4290297647,4290428719,4290559791,4290756399,4290755631,4290755119,4290754607,4290753839,4290753327,4290752559,4290752047,4290751535,4290750767,4290750255,4290749487,4290748975,4290748463,4290747695,4290747183,4290746671,4290745903,4290745391,4290744623,4290744111,4290743599,4290742831,4290742319,4290741551,4290741039,4290740527,4290739759,4290739247,4290738479,4290737967,4290737455,4290736687,4290736175,4290735407,4290734895,4290734383,4290733615,4290733103,4290732591,4290731823,4290731311,4290730543,4290730031,4290729519,4290728751,4290728239,4290727471,4290726959,4290726447,4290725679,4290725167,4290724399,4290723887,4290723375,4290722607,4290722095,4290721327,4290720815,4290720303,4290719535,4290719538,4290719540,4290719542,4290719545,4290719547,4290719550,4290719552,4290719554,4290719557,4290719559,4290719562,4290719564,4290719566,4290719569,4290719571,4290719574,4290719576,4290719578,4290719581,4290719583,4290719586,4290719588,4290719590,4290719593,4290719595,4290719597,4290719600,4290719602,4290719605,4290719607,4290719609,4290719612,4290719614,4290719617,4290719619,4290719621,4290719624,4290719626,4290719629,4290719631,4290719633,4290719636,4290719638,4290719641,4290719643,4290719645,4290719648,4290719650,4290719652,4290719655,4290719657,4290719660,4290719662,4290719664,4290719667,4290719669,4290719672,4290719674,4290719676,4290719679,4290523071,4290391999,4290260927,4290064319,4289933247,4289736639,4289605567,4289474495,4289277887,4289146815,4288950207,4288819135,4288688063,4288491455,4288360383,4288229311,4288032703,4287901631,4287705023,4287573951,4287442879,4287246271,4287115199,4286918591,4286787519,4286656447,4286459839,4286328767,4286132159,4286001087,4285870015,4285673407,4285542335,4285345727,4285214655,4285083583,4284886975,4284755903,4284624831,4284428223,4284297151,4284100543,4283969471,4283838399,4283641791,4283510719,4283314111,4283183039,4283051967,4282855359,4282724287,4282527679,4282396607,4282265535,4282068927,4281937855,4281741247,4281610175,4281479103,4290719679]);
//functions return number from 0 to (maxIter-1)
fractalModule =function(stdlib){
"use asm";
var pow = stdlib.Math.pow;
var abs = stdlib.Math.abs;
var atan2 = stdlib.Math.atan2;
var cos = stdlib.Math.cos;
var sin = stdlib.Math.sin;
function mandlebrot(cx, cy, maxIter) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn = +( pow(x,2) - pow(y,2) + cx);
y = +((x*y)*2 + cy);
x = +xn;
iter=(iter+1)|0;
}
return iter|0;
}
function burningShip(cx, cy, maxIter) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn = pow(x,2) - pow(y,2) - cx;
y = abs(x*y)*2 + cy;
x = xn;
iter=(iter+1)|0;
}
return iter|0;
}
function multibrot(cx, cy, maxIter, cr) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
cr = cr|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
var n1 = +0;
var n2 = +0;
var n3 = +(pow(x,2)+pow(y,2));
while (+n3 < 4 && (iter|0) < (maxIter|0)) {
if(!n3){
x=+cx;
y=+cy;
n3 = +(pow(x,2)+pow(y,2));
continue;
}
n1=pow(n3,(cr>>1));
n2=cr*atan2(y,x);
xn=n1*cos(n2) + cx;
y=n1*sin(n2) + cy;
x = xn;
n3=(pow(x,2)+pow(y,2));
iter=(iter+1)|0;
}
return iter|0;
}
function multibrot3(cx, cy, maxIter) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn=pow(x,3)-3*x*pow(y,2) + cx;
y=3*pow(x,2)*y-pow(y,3) + cy;
x = xn;
iter=(iter+1)|0;
}
return iter|0;
}
function multibrot5(cx, cy, maxIter) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn=pow(x,5)-(10*pow(x,3)*pow(y,2))+(5*x*pow(y,4)) + cx;
y=(5*pow(x,4)*y)-(10*pow(x,2)*pow(y,3))+pow(y,5) + cy;
x = xn;
iter=(iter+1)|0;
}
return iter|0;
}
function tricorn(cx, cy, maxIter) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
var iter=0|0;
var xn= +0;
var x = +0;
var y = +0;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn = pow(x,2) - pow(y,2) - cx;
y =(x+x)*(-y) + cy;
x = xn;
iter=(iter+1)|0;
}
return iter|0;
}
function julia(cx, cy, maxIter, cr, ci) {
cx = +cx;
cy = +cy;
maxIter = maxIter|0;
cr = +cr;
ci = +ci;
var iter=0|0;
var xn= +0;
var x = +cx;
var y = +cy;
while ( +(pow(x,2) + pow(y,2)) < 4&&(iter|0) < (maxIter|0)) {
xn = pow(x,2) - pow(y,2) + cr;
y = (x*y)*2 + ci;
x = xn;
iter=(iter+1)|0;
}
return iter|0;
}
return {
'mandlebrot': mandlebrot,
'burningShip': burningShip,
'multibrot': multibrot,
'multibrot3': multibrot3,
'multibrot5': multibrot5,
'tricorn': tricorn,
'julia': julia
}
}
fractalFunctions=fractalModule(self);
workerFunc = function(data,cb) {
var scale = Math.pow(2, data.z - 1);
var x0 = data.x / scale - 1;
var y0 = data.y / scale - 1;
var d = 1/(scale<<8);
var pixels = new Array(65536);
var MAX_ITER=data.maxIter;
var c,cx,cy,iter,i=0,px,py,a1,a2,a3,a4;
while (i < 65536) {
px = i%256;
py = (i-px)>>8;
cx = x0 + px*d;
cy = y0 + py*d;
iter = fractalFunctions[data.type](cx, cy, MAX_ITER, data.cr, data.ci);
c = ~~((iter/MAX_ITER)*360);
pixels[i++] = colors[c];
pixels[i++] = colors[c];
}
i=1;
while (i < 65536) {
px = i%256;
py = (i-px)>>8;
cx = x0 + px*d;
cy = y0 + py*d;
if(!px||!py||!px%255||py%255){
iter = fractalFunctions[data.type](cx, cy, MAX_ITER, data.cr, data.ci);
c = ~~((iter/MAX_ITER)*360);
pixels[i++] = colors[c];
}
else{
a1=pixels[i+1];
a2=pixels[i-1];
a3=pixels[i+256];
a4=pixels[i-256];
if(a1===a2&&a2===a3&&a3===a4){
i++;
}else{
iter = fractalFunctions[data.type](cx, cy, MAX_ITER, data.cr, data.ci);
c = ~~((iter/MAX_ITER)*360);
pixels[i++] = colors[c];
}
}
i++;
}
var array = new Uint32Array(pixels);
data.pixels = array.buffer;
cb(data,[data.pixels]);
};
self.onmessage=function(e){
workerFunc(e.data,function (a,b){
self.postMessage(a,b);
});
};
}else{
L.TileLayer.FractalLayer = L.TileLayer.Canvas.extend({
options: {
async: true,
maxZoom:23,
continuousWorld:true
},
initialize: function (numWorkers,fractalType,maxIter,cr,ci) {
this.fractalType = fractalType || "mandlebrot";
this.numWorkers = numWorkers;
this._workers = new Array(this.numWorkers);
this.messages={};
this.queue={total: numWorkers};
this.cr = cr || -0.74543;
this.ci = ci || 0.11301;
this.maxIter = maxIter || 500;
var scripts = document.getElementsByTagName("script");
var len = scripts.length;
var i = 0;
while(i<len){
if(/FractalLayer\.js/.test(scripts[i].src)){
this.workerPath=scripts[i].src;
break;
}
i++;
}
},
onAdd: function(map) {
var _this = this;
var i = 0;
var next;
this.queue.free = [];
this.queue.len =0;
this.queue.tiles = [];
while(i<this.numWorkers){
this.queue.free.push(i);
this._workers[i]=new Worker(this.workerPath);
this._workers[i].onmessage=function(e) {
var canvas;
if(_this.queue.len) {
_this.queue.len--;
next = _this.queue.tiles.shift();
_this._renderTile(next[0],next[1],e.data.workerID);
} else {
_this.queue.free.push(e.data.workerID);
}
if (e.data.tileID in _this.messages) {
canvas = _this.messages[e.data.tileID];
} else {
return;
}
var array=new Uint8Array(e.data.pixels);
var ctx = canvas.getContext('2d');
var imagedata = ctx.getImageData(0, 0, 256, 256);
imagedata.data.set(array);
ctx.putImageData(imagedata, 0, 0);
_this.tileDrawn(canvas);
};
i++;
}
this.on("tileunload", function(e) {
if(e.tile._tileIndex){
var pos = e.tile._tileIndex,
tileID = [pos.x, pos.y, pos.z].join(':');
if(tileID in _this.messages){
delete _this.messages[tileID];
}
}
});
map.on("zoomstart",function() {
this.queue.len = 0;
this.queue.tiles = [];
}, this);
return L.TileLayer.Canvas.prototype.onAdd.call(this,map);
},
onRemove:function(map){
this.messages={};
var len = this._workers.length;
var i =0;
while(i<len){
this._workers[i].terminate();
i++;
}
return L.TileLayer.Canvas.prototype.onRemove.call(this,map);
},
drawTile: function (canvas, tilePoint) {
if(!this.queue.free.length){
this.queue.tiles.push([canvas,tilePoint]);
this.queue.len++;
}else{
this._renderTile(canvas, tilePoint,this.queue.free.pop());
}
},
_renderTile: function (canvas, tilePoint,workerID) {
var z = this._map.getZoom();
canvas._tileIndex = {x: tilePoint.x, y: tilePoint.y, z: z};
var tileID=tilePoint.x+":"+tilePoint.y+":"+z;
this.messages[tileID]=canvas;
this._workers[workerID].postMessage({
x: tilePoint.x,
y:tilePoint.y,
z: z,
tileID: tileID,
workerID: workerID,
cr: this.cr,
ci: this.ci,
maxIter: this.maxIter,
type: this.fractalType
});
}
});
L.tileLayer.fractalLayer = function(numWorkers,t,mi,cr,ci){
return new L.TileLayer.FractalLayer(numWorkers,t,mi,cr,ci);
}} | no string keys
| FractalLayer.js | no string keys | <ide><path>ractalLayer.js
<ide> return iter|0;
<ide> }
<ide> return {
<del> 'mandlebrot': mandlebrot,
<del> 'burningShip': burningShip,
<del> 'multibrot': multibrot,
<del> 'multibrot3': multibrot3,
<del> 'multibrot5': multibrot5,
<del> 'tricorn': tricorn,
<del> 'julia': julia
<del>}
<del>
<del>}
<add> mandlebrot: mandlebrot,
<add> burningShip: burningShip,
<add> multibrot: multibrot,
<add> multibrot3: multibrot3,
<add> multibrot5: multibrot5,
<add> tricorn: tricorn,
<add> julia: julia
<add>};
<add>
<add>};
<ide> fractalFunctions=fractalModule(self);
<ide> workerFunc = function(data,cb) {
<ide> var scale = Math.pow(2, data.z - 1); |
|
Java | mit | b291458cd1f49f5662948c3f0726cd9d1987985d | 0 | bitcoin-solutions/multibit-hd,bitcoin-solutions/multibit-hd,akonring/multibit-hd-modified,oscarguindzberg/multibit-hd,oscarguindzberg/multibit-hd,oscarguindzberg/multibit-hd,akonring/multibit-hd-modified,akonring/multibit-hd-modified,bitcoin-solutions/multibit-hd | mbhd-core/src/main/java/org/multibit/hd/core/managers/MultiBitCheckpointManager.java | package org.multibit.hd.core.managers;
import org.bitcoinj.core.CheckpointManager;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.StoredBlock;
import org.bitcoinj.core.VerificationException;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
// TODO (JB) This class is not used - delete it?
public class MultiBitCheckpointManager extends CheckpointManager {
public MultiBitCheckpointManager(NetworkParameters params, String checkpointFilename) throws IOException {
// The created fileInputStream is closed in the super.
super(params, new FileInputStream(checkpointFilename));
}
/**
* Returns a {@link org.bitcoinj.core.StoredBlock} representing the last managers before the given block height, for example, normally
* you would want to know the managers before the last block the wallet had seen.
*/
public StoredBlock getCheckpointBeforeOrAtHeight(int height) {
Map.Entry<Long, StoredBlock> highestCheckpointBeforeHeight = null;
for (Map.Entry<Long, StoredBlock> loop : checkpoints.entrySet()) {
if (loop.getValue().getHeight() < height) {
// This managers is before the specified height.
if (highestCheckpointBeforeHeight == null) {
highestCheckpointBeforeHeight = loop;
} else {
if (highestCheckpointBeforeHeight.getValue().getHeight() < loop.getValue().getHeight()) {
// This entry is later.
highestCheckpointBeforeHeight = loop;
}
}
}
}
if (highestCheckpointBeforeHeight == null) {
try {
return new StoredBlock(params.getGenesisBlock(), params.getGenesisBlock().getWork(), 0);
} catch (VerificationException e) {
e.printStackTrace();
}
}
return highestCheckpointBeforeHeight.getValue();
}
} | #323 Findbugs: Remove unused class (MultiBitCheckpointManager) which contained potential NPE
| mbhd-core/src/main/java/org/multibit/hd/core/managers/MultiBitCheckpointManager.java | #323 Findbugs: Remove unused class (MultiBitCheckpointManager) which contained potential NPE | <ide><path>bhd-core/src/main/java/org/multibit/hd/core/managers/MultiBitCheckpointManager.java
<del>package org.multibit.hd.core.managers;
<del>
<del>import org.bitcoinj.core.CheckpointManager;
<del>import org.bitcoinj.core.NetworkParameters;
<del>import org.bitcoinj.core.StoredBlock;
<del>import org.bitcoinj.core.VerificationException;
<del>
<del>import java.io.FileInputStream;
<del>import java.io.IOException;
<del>import java.util.Map;
<del>
<del>// TODO (JB) This class is not used - delete it?
<del>public class MultiBitCheckpointManager extends CheckpointManager {
<del>
<del>
<del> public MultiBitCheckpointManager(NetworkParameters params, String checkpointFilename) throws IOException {
<del>
<del> // The created fileInputStream is closed in the super.
<del> super(params, new FileInputStream(checkpointFilename));
<del> }
<del>
<del> /**
<del> * Returns a {@link org.bitcoinj.core.StoredBlock} representing the last managers before the given block height, for example, normally
<del> * you would want to know the managers before the last block the wallet had seen.
<del> */
<del> public StoredBlock getCheckpointBeforeOrAtHeight(int height) {
<del> Map.Entry<Long, StoredBlock> highestCheckpointBeforeHeight = null;
<del>
<del> for (Map.Entry<Long, StoredBlock> loop : checkpoints.entrySet()) {
<del> if (loop.getValue().getHeight() < height) {
<del> // This managers is before the specified height.
<del> if (highestCheckpointBeforeHeight == null) {
<del> highestCheckpointBeforeHeight = loop;
<del> } else {
<del> if (highestCheckpointBeforeHeight.getValue().getHeight() < loop.getValue().getHeight()) {
<del> // This entry is later.
<del> highestCheckpointBeforeHeight = loop;
<del> }
<del> }
<del> }
<del> }
<del>
<del> if (highestCheckpointBeforeHeight == null) {
<del> try {
<del> return new StoredBlock(params.getGenesisBlock(), params.getGenesisBlock().getWork(), 0);
<del> } catch (VerificationException e) {
<del> e.printStackTrace();
<del> }
<del> }
<del> return highestCheckpointBeforeHeight.getValue();
<del> }
<del>} |
||
JavaScript | mit | c210f7abd9295a3c0b6413e6561a626e8d7dd4ab | 0 | Symfony-Plugins/sfDoctrineActAsTaggablePlugin,Symfony-Plugins/sfDoctrineActAsTaggablePlugin | // You need to bring in jQuery first in order for this to work
//
// Call it like this:
// pkTagahead(<?php echo json_encode(url_for("taggableComplete/complete")) ?>);
//
// Or similar. Now all of your input elements with the input-tag class
// automatically gain the typeahead suggestion feature.
//
// If you're not using Symfony and sfDoctrineActAsTaggablePlugin,
// pass your own URL that returns a <ul> containing <li>s with the
// FULL TEXT of what the ENTIRE tag string will be if the user takes
// that suggestion, with the new tag you're suggesting an <a> link
// to #. Then use CSS to hide (visibility: none) the part of the
// <li> that is not in the <a>. Don't introduce any extra whitespace.
function pkTagahead(tagaheadUrl)
{
$(function() {
function getKey(event)
{
// Portable keycodes sigh
return event.keyCode ? event.keyCode : event.which;
}
function setClick(target)
{
$(target).find('a').click(function(event)
{
// span contains ul contains li contains a
var span = this.parentNode.parentNode.parentNode;
var input = $(span).data("tag-peer");
// Get text from the li
var parent = this.parentNode;
$(input).val($(parent).text());
$(input).focus();
return false;
});
}
// Add suggestions span (you'll need to style that)
$('input.tag-input').after("<div class='tag-suggestions'></div>");
// Each tag field remembers its suggestions span...
$('input.tag-input').each(function()
{
$(this).data("tag-peer", $(this).next()[0]);
});
// And vice versa
$('div.tag-suggestions').each(function()
{
$(this).data("tag-peer", $(this).prev()[0]);
});
// Now we can really throw down
$('input.tag-input').keyup(function(event)
{
var key = getKey(event);
// Tab key
if (key == 9)
{
var peer = $(this).data("tag-peer");
var suggestions = $(peer).find("li");
if (suggestions.length)
{
$(this).val($(suggestions[0]).text());
$(this).focus();
}
// In any case don't insert the tab
return false;
}
else
{
// Trigger ajax update of suggestions
}
});
$('input.tag-input').keypress(function(event)
{
// Firefox 2.0 mac is stubborn and only allows cancel here
// (we will still get the keyup and do the real work there)
var key = getKey(event);
if (key == 9)
{
// Don't insert tabs, ever
return false;
}
});
var lastValues = {};
setInterval(function()
{
// AJAX query for suggestions only when changes have taken place
$('input.tag-input').each(function()
{
var last = $(this).data('tag-last');
var value = $(this).val();
var peer = $(this).data('tag-peer');
if (last !== value)
{
$(this).data('tag-last', value);
$.post(
tagaheadUrl,
{
current: $(this).val()
},
function(data, textStatus)
{
$(peer).html(data);
setClick(peer);
}
);
}
});
}, 200);
});
}
function pkInlineTaggableWidget(selector, options)
{
$(selector).each(function()
{
// Semi-global
var typeaheadUrl = options['typeahead-url'];
var tagsLabel = options['tags-label'];
var popularTags = options['popular-tags'];
var existingTags = {};
var allTags = options['all-tags'];
var commitSelector = options['commit-selector'];
var commitEvent = options['commit-event'];
if (typeof(tagsLabel) == 'undefined')
{
tagsLabel = "Existing Tags";
};
if (typeof(popularTags) == 'undefined')
{
popularTags = {};
};
if (typeof(allTags) == 'undefined')
{
allTags == {};
};
if (typeof(commitEvent) == 'undefined')
{
commitEvent = 'click';
}
// populate existingTags
if ($(this).val().trim() != '')
{
var lp = $(this).val().split(',');
for (x in lp)
{
existingTags[lp[x].trim()] = lp[x].trim();
}
}
function makePopularLink(attributes, title, text)
{
var new_tag = $('<span />');
var new_link = $('<a />');
new_tag.html("<span>"+text+"</span>");
new_tag.attr({ title: title }).addClass('a-tag a-popular');
new_tag.prepend(new_link);
new_link.text(title);
new_link.attr(attributes);
return new_tag;
}
function makeRemoveLink(attributes, title, text)
{
title = $.trim(title);
var new_tag = $('<span />');
var new_link = $('<a />');
var tagTitle = title;
if (typeof(allTags) != 'undefined')
{
if (typeof(allTags[title]) != 'undefined')
{
title = title + ' - ' + allTags[title];
}
else
{
title = title + ' - 0';
}
}
new_tag.html("<span>"+title+"</span>");
new_tag.attr({ title: tagTitle }).addClass('a-tag');
new_link.text('Remove Tag');
new_link.attr(attributes);
new_link.attr({ title: 'Remove' }).addClass('a-btn icon a-close-small no-label no-bg');
new_link.prepend('<span class="icon"></span>');
new_tag.append(new_link);
return new_tag;
}
function trimExcessCommas(string)
{
string = string.replace(/(^,)|(, ?$)/g, '');
string = string.replace(/(,,)|(, ,)/, ',');
string = $.trim(string);
return string;
}
// We don't want to display popular tags that we're already using
var unusedPopulars = {};
for (x in popularTags)
{
if (typeof(existingTags[x]) == 'undefined')
{
unusedPopulars[x] = popularTags[x];
}
}
var popularsAttributes = {};
var existingTagsAttributes = {};
var existingDiv = $('<div />');
var popularsDiv = $('<div />');
// Establish the quick enhancement
var tagInput = $(this);
var typeAheadContainer = $('<div />');
var typeAheadBox = $('<input />');
var typeAheadBoxId = 'inline-tag-ahead-box-' + Math.floor(Math.random() * 2000);
typeAheadBox.attr('type', 'text');
typeAheadBox.attr('id', typeAheadBoxId);
if ((typeof(allTags) == 'undefined') && (typeof(typeaheadUrl) != 'undefined'))
{
typeAheadBox.autocomplete(typeaheadUrl, { multiple: true });
}
else if (typeof(allTags) != 'undefined')
{
var allTagsReformat = new Array();
for (x in allTags)
{
allTagsReformat.push(x);
}
typeAheadBox.autocomplete(allTagsReformat, { multiple: true })
}
var addButton = $('<a />');
addButton.html('<span class="icon"></span>Add');
addButton.attr({'href' : '#', 'class' : 'a-btn icon a-add add-tags-link', 'title' : 'Add these tags'});
typeAheadContainer.addClass('a-inline-taggable-widget').append(typeAheadBox).append(addButton);
tagInput.hide();
tagInput.parent().append(typeAheadContainer);
// Add a list of popular tags to be added
function addTagsToForm(link)
{
var tag = link.attr('title');
var value = tagInput.val() + ', ' + tag;
value = trimExcessCommas(value);
tagInput.val(value);
link.remove();
var new_link = makeRemoveLink(existingTagsAttributes, tag, tag + ' x');
new_link.children('a').bind('click', function() { removeTagsFromForm($(this).parent()); return false; });
existingDiv.append(new_link);
}
// Add a list of tags that may be removed
function removeTagsFromForm(link)
{
var tag = link.attr('title');
var value = tagInput.val();
value = value.replace(tag, '');
value = trimExcessCommas(value);
tagInput.val(value);
link.remove();
// As we have just removed it from the list, we want the real deal populars.
if (typeof(popularTags[tag]) != 'undefined')
{
var linkLabel = popularTags[tag];
var new_link = makePopularLink(existingTagsAttributes, tag, linkLabel);
new_link.children('a').bind('click', function() { addTagsToForm($(this).parent()); return false; });
popularsDiv.append(new_link);
}
}
// a maker function for tag containers
function makeTagContainer(containerLabel, tagArray, linkAttributes, linkLabelType)
{
// Add a list of tags that may be removed
var tagContainer = $('<div />');
tagContainer.addClass('a-inline-taggable-widget-tag-container');
var header = $('<h4 />');
header.text(containerLabel);
tagContainer.append(header);
var attributes = {};
for (x in tagArray)
{
var linkLabel = '';
if (linkLabelType == 'add')
{
tagContainer.addClass('a-popular-tags');
linkLabel = tagArray[x];
var new_link = makePopularLink(linkAttributes, x, linkLabel);
new_link.children('a').bind('click', function() { addTagsToForm($(this).parent()); return false; });
}
else if (linkLabelType == 'remove')
{
tagContainer.addClass('a-existing-tags');
linkLabel = 'x ' + x;
var new_link = makeRemoveLink(linkAttributes, x, linkLabel);
new_link.children('a').bind('click', function() { removeTagsFromForm($(this).parent()); return false; });
}
tagContainer.append(new_link);
}
return tagContainer;
}
// Add the new tags to the existing form input.
// If the user doesn't click Save changes or add... tough?
function commitTagsToForm()
{
if (typeAheadBox.val() != '')
{
var value = tagInput.val() + ',' + typeAheadBox.val();
value = trimExcessCommas(value);
tagInput.val(value);
typeAheadBox.val('');
existingTags = {};
var lp = value.split(',');
for (x in lp)
{
existingTags[lp[x]] = lp[x];
}
existingDiv.html(makeTagContainer(tagsLabel, existingTags, existingTagsAttributes, 'remove').html());
existingDiv.find('a').each(function() {
$(this).bind('click', function() {
removeTagsFromForm($(this).parent());
return false;
});
});
}
return false;
}
addButton.bind('click', function() { commitTagsToForm(); return false; });
if (commitSelector != 'undefined')
{
$(commitSelector).bind(commitEvent, function() {
commitTagsToForm();
return true;
});
}
existingDiv = makeTagContainer(tagsLabel, existingTags, existingTagsAttributes, 'remove');
existingDiv.children('a').bind('click', function() { removeTagsFromForm($(this)); return false; });
tagInput.parent().prepend(existingDiv);
popularsDiv = makeTagContainer('Popular Tags', unusedPopulars, popularsAttributes, 'add');
popularsDiv.children('a').bind('click', function() { addTagsToForm($(this)); return false; });
tagInput.parent().append(popularsDiv);
// Catch that enter key, baby!
$(document).keyup(function(e)
{
if (e.keyCode == 13)
{
e.preventDefault();
}
});
$(document).keypress(function(e)
{
if (e.keyCode == 13)
{
e.preventDefault();
}
});
typeAheadBox.keyup(function(e)
{
if (e.keyCode == 13)
{
commitTagsToForm();
}
});
});
}
| web/js/pkTagahead.js | // You need to bring in jQuery first in order for this to work
//
// Call it like this:
// pkTagahead(<?php echo json_encode(url_for("taggableComplete/complete")) ?>);
//
// Or similar. Now all of your input elements with the input-tag class
// automatically gain the typeahead suggestion feature.
//
// If you're not using Symfony and sfDoctrineActAsTaggablePlugin,
// pass your own URL that returns a <ul> containing <li>s with the
// FULL TEXT of what the ENTIRE tag string will be if the user takes
// that suggestion, with the new tag you're suggesting an <a> link
// to #. Then use CSS to hide (visibility: none) the part of the
// <li> that is not in the <a>. Don't introduce any extra whitespace.
function pkTagahead(tagaheadUrl)
{
$(function() {
function getKey(event)
{
// Portable keycodes sigh
return event.keyCode ? event.keyCode : event.which;
}
function setClick(target)
{
$(target).find('a').click(function(event)
{
// span contains ul contains li contains a
var span = this.parentNode.parentNode.parentNode;
var input = $(span).data("tag-peer");
// Get text from the li
var parent = this.parentNode;
$(input).val($(parent).text());
$(input).focus();
return false;
});
}
// Add suggestions span (you'll need to style that)
$('input.tag-input').after("<div class='tag-suggestions'></div>");
// Each tag field remembers its suggestions span...
$('input.tag-input').each(function()
{
$(this).data("tag-peer", $(this).next()[0]);
});
// And vice versa
$('div.tag-suggestions').each(function()
{
$(this).data("tag-peer", $(this).prev()[0]);
});
// Now we can really throw down
$('input.tag-input').keyup(function(event)
{
var key = getKey(event);
// Tab key
if (key == 9)
{
var peer = $(this).data("tag-peer");
var suggestions = $(peer).find("li");
if (suggestions.length)
{
$(this).val($(suggestions[0]).text());
$(this).focus();
}
// In any case don't insert the tab
return false;
}
else
{
// Trigger ajax update of suggestions
}
});
$('input.tag-input').keypress(function(event)
{
// Firefox 2.0 mac is stubborn and only allows cancel here
// (we will still get the keyup and do the real work there)
var key = getKey(event);
if (key == 9)
{
// Don't insert tabs, ever
return false;
}
});
var lastValues = {};
setInterval(function()
{
// AJAX query for suggestions only when changes have taken place
$('input.tag-input').each(function()
{
var last = $(this).data('tag-last');
var value = $(this).val();
var peer = $(this).data('tag-peer');
if (last !== value)
{
$(this).data('tag-last', value);
$.post(
tagaheadUrl,
{
current: $(this).val()
},
function(data, textStatus)
{
$(peer).html(data);
setClick(peer);
}
);
}
});
}, 200);
});
}
function pkInlineTaggableWidget(selector, options)
{
$(selector).each(function()
{
// Semi-global
var typeaheadUrl = options['typeahead-url'];
var tagsLabel = options['tags-label'];
var popularTags = options['popular-tags'];
var existingTags = {};
var allTags = options['all-tags'];
var commitSelector = options['commit-selector'];
var commitEvent = options['commit-event'];
if (typeof(tagsLabel) == 'undefined')
{
tagsLabel = "Existing Tags";
};
if (typeof(popularTags) == 'undefined')
{
popularTags = {};
};
if (typeof(allTags) == 'undefined')
{
allTags == {};
};
if (typeof(commitEvent) == 'undefined')
{
commitEvent = 'click';
}
// populate existingTags
if ($(this).val().trim() != '')
{
var lp = $(this).val().split(',');
for (x in lp)
{
existingTags[lp[x].trim()] = lp[x].trim();
}
}
function makePopularLink(attributes, title, text)
{
var new_tag = $('<span />');
var new_link = $('<a />');
new_tag.html("<span>"+text+"</span>");
new_tag.attr({ title: title }).addClass('a-tag a-popular');
new_tag.prepend(new_link);
new_link.text(title);
new_link.attr(attributes);
return new_tag;
}
function makeRemoveLink(attributes, title, text)
{
title = $.trim(title);
var new_tag = $('<span />');
var new_link = $('<a />');
var tagTitle = title;
if (typeof(allTags) != 'undefined')
{
if (typeof(allTags[title]) != 'undefined')
{
title = title + ' - ' + allTags[title];
}
else
{
title = title + ' - 0';
}
}
new_tag.html("<span>"+title+"</span>");
new_tag.attr({ title: tagTitle }).addClass('a-tag');
new_link.text('Remove Tag');
new_link.attr(attributes);
new_link.attr({ title: 'Remove' }).addClass('a-btn icon a-close-small no-label no-bg');
new_link.prepend('<span class="icon"></span>');
new_tag.append(new_link);
return new_tag;
}
function trimExcessCommas(string)
{
string = string.replace(/(^,)|(, ?$)/g, '');
string = string.replace(/(,,)|(, ,)/, ',');
string = $.trim(string);
return string;
}
// We don't want to display popular tags that we're already using
var unusedPopulars = {};
for (x in popularTags)
{
if (typeof(existingTags[x]) == 'undefined')
{
unusedPopulars[x] = popularTags[x];
}
}
var popularsAttributes = {};
var existingTagsAttributes = {};
var existingDiv = $('<div />');
var popularsDiv = $('<div />');
// Establish the quick enhancement
var tagInput = $(this);
var typeAheadContainer = $('<div />');
var typeAheadBox = $('<input />');
var typeAheadBoxId = 'inline-tag-ahead-box-' + Math.floor(Math.random() * 2000);
typeAheadBox.attr('type', 'text');
typeAheadBox.attr('id', typeAheadBoxId);
if ((typeof(allTags) == 'undefined') && (typeof(typeaheadUrl) != 'undefined'))
{
typeAheadBox.autocomplete(typeaheadUrl, { multiple: true });
}
else if (typeof(allTags) != 'undefined')
{
var allTagsReformat = new Array();
for (x in allTags)
{
allTagsReformat.push(x);
}
typeAheadBox.autocomplete(allTagsReformat, { multiple: true })
}
var addButton = $('<a />');
addButton.html('<span class="icon"></span>Add');
addButton.attr({'href' : '#', 'class' : 'a-btn icon a-add add-tags-link', 'title' : 'Add these tags'});
typeAheadContainer.addClass('a-inline-taggable-widget').append(typeAheadBox).append(addButton);
tagInput.hide();
tagInput.parent().append(typeAheadContainer);
// Add a list of popular tags to be added
function addTagsToForm(link)
{
var tag = link.attr('title');
var value = tagInput.val() + ', ' + tag;
value = trimExcessCommas(value);
tagInput.val(value);
link.remove();
var new_link = makeRemoveLink(existingTagsAttributes, tag, tag + ' x');
new_link.children('a').bind('click', function() { removeTagsFromForm($(this).parent()); return false; });
existingDiv.append(new_link);
}
// Add a list of tags that may be removed
function removeTagsFromForm(link)
{
var tag = link.attr('title');
var value = tagInput.val();
value = value.replace(tag, '');
value = trimExcessCommas(value);
tagInput.val(value);
link.remove();
// As we have just removed it from the list, we want the real deal populars.
if (typeof(popularTags[tag]) != 'undefined')
{
var linkLabel = popularTags[tag];
var new_link = makePopularLink(existingTagsAttributes, tag, linkLabel);
new_link.children('a').bind('click', function() { addTagsToForm($(this).parent()); return false; });
popularsDiv.append(new_link);
}
}
// a maker function for tag containers
function makeTagContainer(containerLabel, tagArray, linkAttributes, linkLabelType)
{
// Add a list of tags that may be removed
var tagContainer = $('<div />');
tagContainer.addClass('a-inline-taggable-widget-tag-container');
var header = $('<h4 />');
header.text(containerLabel);
tagContainer.append(header);
var attributes = {};
for (x in tagArray)
{
var linkLabel = '';
if (linkLabelType == 'add')
{
tagContainer.addClass('a-popular-tags');
linkLabel = tagArray[x];
var new_link = makePopularLink(linkAttributes, x, linkLabel);
new_link.children('a').bind('click', function() { addTagsToForm($(this).parent()); return false; });
}
else if (linkLabelType == 'remove')
{
tagContainer.addClass('a-existing-tags');
linkLabel = 'x ' + x;
var new_link = makeRemoveLink(linkAttributes, x, linkLabel);
new_link.children('a').bind('click', function() { removeTagsFromForm($(this).parent()); return false; });
}
tagContainer.append(new_link);
}
return tagContainer;
}
// Add the new tags to the existing form input.
// If the user doesn't click Save changes or add... tough?
function commitTagsToForm()
{
var value = tagInput.val() + ',' + typeAheadBox.val();
value = trimExcessCommas(value);
tagInput.val(value);
typeAheadBox.val('');
existingTags = {};
var lp = value.split(',');
for (x in lp)
{
existingTags[lp[x]] = lp[x];
}
existingDiv.html(makeTagContainer(tagsLabel, existingTags, existingTagsAttributes, 'remove').html());
existingDiv.find('a').each(function() {
$(this).bind('click', function() {
removeTagsFromForm($(this).parent());
return false;
});
});
return false;
}
addButton.bind('click', function() { commitTagsToForm(); return false; });
if (commitSelector != 'undefined')
{
$(commitSelector).bind(commitEvent, function() {
commitTagsToForm();
return true;
});
}
existingDiv = makeTagContainer(tagsLabel, existingTags, existingTagsAttributes, 'remove');
existingDiv.children('a').bind('click', function() { removeTagsFromForm($(this)); return false; });
tagInput.parent().prepend(existingDiv);
popularsDiv = makeTagContainer('Popular Tags', unusedPopulars, popularsAttributes, 'add');
popularsDiv.children('a').bind('click', function() { addTagsToForm($(this)); return false; });
tagInput.parent().append(popularsDiv);
// Catch that enter key, baby!
$(document).keyup(function(e)
{
if (e.keyCode == 13)
{
e.preventDefault();
}
});
$(document).keypress(function(e)
{
if (e.keyCode == 13)
{
e.preventDefault();
}
});
typeAheadBox.keyup(function(e)
{
if (e.keyCode == 13)
{
commitTagsToForm();
}
});
});
}
| Ticket #667
git-svn-id: 14431f16c86e063b591b7186ad64c5043b5760e0@31206 ee427ae8-e902-0410-961c-c3ed070cd9f9
| web/js/pkTagahead.js | Ticket #667 | <ide><path>eb/js/pkTagahead.js
<ide> // If the user doesn't click Save changes or add... tough?
<ide> function commitTagsToForm()
<ide> {
<del> var value = tagInput.val() + ',' + typeAheadBox.val();
<del> value = trimExcessCommas(value);
<del> tagInput.val(value);
<del> typeAheadBox.val('');
<del>
<del> existingTags = {};
<del> var lp = value.split(',');
<del> for (x in lp)
<del> {
<del> existingTags[lp[x]] = lp[x];
<del> }
<del>
<del> existingDiv.html(makeTagContainer(tagsLabel, existingTags, existingTagsAttributes, 'remove').html());
<del> existingDiv.find('a').each(function() {
<del> $(this).bind('click', function() {
<del> removeTagsFromForm($(this).parent());
<del> return false;
<add> if (typeAheadBox.val() != '')
<add> {
<add> var value = tagInput.val() + ',' + typeAheadBox.val();
<add> value = trimExcessCommas(value);
<add> tagInput.val(value);
<add> typeAheadBox.val('');
<add>
<add> existingTags = {};
<add> var lp = value.split(',');
<add> for (x in lp)
<add> {
<add> existingTags[lp[x]] = lp[x];
<add> }
<add>
<add> existingDiv.html(makeTagContainer(tagsLabel, existingTags, existingTagsAttributes, 'remove').html());
<add> existingDiv.find('a').each(function() {
<add> $(this).bind('click', function() {
<add> removeTagsFromForm($(this).parent());
<add> return false;
<add> });
<ide> });
<del> });
<del>
<add> }
<ide> return false;
<ide> }
<ide> addButton.bind('click', function() { commitTagsToForm(); return false; }); |
|
Java | mit | 9185eab9739db63f15ab4b0ed70e44e1ac2d5f95 | 0 | AnnAddicks/sendash,AnnAddicks/sendash,AnnAddicks/sendash,AnnAddicks/sendash,AnnAddicks/sendash | package com.addicks.sendash.admin.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.addicks.sendash.admin.domain.properties.RepositoryProperties;
@Service
public class FileService {
@Autowired
private RepositoryProperties repositoryProperties;
private static final Logger log = LoggerFactory.getLogger(FileService.class);
public FileService() {
}
private List<String> generateFileList(String sourceFolder, File node) throws IOException {
List<String> fileList = new ArrayList<String>();
// add file only
if (node.isFile()) {
fileList.add(node.getCanonicalPath());
}
if (node.isDirectory()) {
String[] subNote = node.list();
for (String filename : subNote) {
if (!filename.startsWith(".")) {
fileList.addAll(generateFileList(sourceFolder, new File(node, filename)));
}
}
}
return fileList;
}
public void createZip() {
String zipFile = repositoryProperties.getZipOfRep();
String sourceDirectory = repositoryProperties.getLocalRepo();
byte[] buffer = new byte[1024];
try {
// create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(zipFile);
// create object of ZipOutputStream from FileOutputStream
try (ZipOutputStream zout = new ZipOutputStream(fout)) {
// create File object from directory name
File dir = new File(sourceDirectory);
log.debug("DIR: " + dir);
// check to see if this directory exists
if (!dir.isDirectory()) {
log.error(sourceDirectory + " is not a directory");
}
else {
List<String> files = generateFileList(sourceDirectory, dir);
for (String fileName : files) {
// create object of FileInputStream for source file
try {
FileInputStream fin = new FileInputStream(fileName);
zout.putNextEntry(new ZipEntry(fileName.replace("/home/tomcat7/", "")));
/*
* After creating entry in the zip file, actually write the file.
*/
int length;
while ((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
}
catch (FileNotFoundException ex) {
log.error("File not Found:" + fileName);
}
}
}
// close the ZipOutputStream
zout.close();
log.debug("Zip file has been created!");
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
public ZipInputStream getZip() throws IOException {
File zipFile = new File(repositoryProperties.getZipOfRep());
return new ZipInputStream(new FileInputStream(zipFile));
}
}
| src/main/java/com/addicks/sendash/admin/service/FileService.java | package com.addicks.sendash.admin.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.addicks.sendash.admin.domain.properties.RepositoryProperties;
@Service
public class FileService {
@Autowired
private RepositoryProperties repositoryProperties;
private static final Logger log = LoggerFactory.getLogger(FileService.class);
public FileService() {
}
private List<String> generateFileList(String sourceFolder, File node) throws IOException {
List<String> fileList = new ArrayList<String>();
// add file only
if (node.isFile()) {
fileList.add(node.getCanonicalPath());
}
if (node.isDirectory()) {
String[] subNote = node.list();
for (String filename : subNote) {
if (!filename.startsWith(".")) {
fileList.addAll(generateFileList(sourceFolder, new File(node, filename)));
}
}
}
return fileList;
}
public void createZip() {
String zipFile = repositoryProperties.getZipOfRep();
String sourceDirectory = repositoryProperties.getLocalRepo();
byte[] buffer = new byte[1024];
try {
// create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(zipFile);
// create object of ZipOutputStream from FileOutputStream
try (ZipOutputStream zout = new ZipOutputStream(fout)) {
// create File object from directory name
File dir = new File(sourceDirectory);
log.debug("DIR: " + dir);
// check to see if this directory exists
if (!dir.isDirectory()) {
log.error(sourceDirectory + " is not a directory");
}
else {
List<String> files = generateFileList(sourceDirectory, dir);
log.error("*************");
String startingDir = repositoryProperties.getZipOfRep();
for (String fileName : files) {
// create object of FileInputStream for source file
try {
log.error("FileName: " + fileName);
log.error("Starting Dir: " + startingDir);
FileInputStream fin = new FileInputStream(fileName);
zout.putNextEntry(new ZipEntry(fileName.replace(startingDir, "")));
log.error("substring" + fileName.replace(startingDir, ""));
/*
* After creating entry in the zip file, actually write the file.
*/
int length;
while ((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
}
catch (FileNotFoundException ex) {
log.error("File not Found:" + fileName);
}
}
}
log.error("*************");
// close the ZipOutputStream
zout.close();
log.debug("Zip file has been created!");
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
public ZipInputStream getZip() throws IOException {
File zipFile = new File(repositoryProperties.getZipOfRep());
return new ZipInputStream(new FileInputStream(zipFile));
}
}
| removed logs
| src/main/java/com/addicks/sendash/admin/service/FileService.java | removed logs | <ide><path>rc/main/java/com/addicks/sendash/admin/service/FileService.java
<ide> }
<ide> else {
<ide> List<String> files = generateFileList(sourceDirectory, dir);
<del> log.error("*************");
<del> String startingDir = repositoryProperties.getZipOfRep();
<add>
<ide> for (String fileName : files) {
<ide>
<ide> // create object of FileInputStream for source file
<ide> try {
<del>
<del> log.error("FileName: " + fileName);
<del> log.error("Starting Dir: " + startingDir);
<ide> FileInputStream fin = new FileInputStream(fileName);
<del> zout.putNextEntry(new ZipEntry(fileName.replace(startingDir, "")));
<del> log.error("substring" + fileName.replace(startingDir, ""));
<add> zout.putNextEntry(new ZipEntry(fileName.replace("/home/tomcat7/", "")));
<ide>
<ide> /*
<ide> * After creating entry in the zip file, actually write the file.
<ide> }
<ide> }
<ide> }
<del> log.error("*************");
<add>
<ide> // close the ZipOutputStream
<ide> zout.close();
<ide> |
|
Java | mit | ac3526af1cf823413640dd08ab7eead4eea7d729 | 0 | D-PLAN/Vibernate-2 | package com.napontaratan.vibernate;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.*;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.napontaratan.vibernate.model.TimerConflictException;
import com.napontaratan.vibernate.model.TimerSession;
import com.napontaratan.vibernate.model.TimerSessionHolder;
import com.napontaratan.vibernate.view.ColorPickerDialog;
import com.napontaratan.vibernate.view.ColorPickerSwatch;
import com.napontaratan.vibernate.view.CreateTimerTimePicker;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
public class CreateTimerActivity extends FragmentActivity implements TimePickerDialog.OnTimeSetListener {
private static String COLOR_CAL_TAG = "cal";
private static String START_TIME_TAG = "start";
private static String END_TIME_TAG = "end";
public static String KEY_HOUR = "hour";
public static String KEY_MINUTE = "minute";
// if modifying a timer, the information is passed through a bundle
private TimerSession bundledTimer;
private boolean[] bundledTimerDays; // used to compare if timer has changed
// ELEMENTS
private CreateTimerTimePicker timePicker;
private ColorPickerDialog colorPicker;
private Toolbar toolbar;
private Dialog dialog;
private EditText nameField;
private TextView start_time_display;
private TextView end_time_display;
private ToggleButton vibrate_toggle;
private ToggleButton silent_toggle;
private ToggleButton weekdays_toggle;
private ToggleButton weekends_toggle;
private List<ToggleButton> toggle_btn_days;
private boolean[] boolean_days = new boolean[7];
private ImageButton done;
// VALUES
private int colorPicked;
// @Override
// protected void onStart() {
// super.onStart();
// GoogleAnalytics.getInstance(this).reportActivityStart(this);
// }
//
// @Override
// protected void onStop() {
// super.onStop();
// GoogleAnalytics.getInstance(this).reportActivityStop(this);
// }
public void setupElements() {
nameField = (EditText) findViewById(R.id.create_timer_name_field);
nameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
nameField.clearFocus();
vibrate_toggle = (ToggleButton) findViewById(R.id.create_timer_type_vibrate);
silent_toggle = (ToggleButton) findViewById(R.id.create_timer_type_silent);
timePicker = new CreateTimerTimePicker();
start_time_display = (TextView) findViewById(R.id.create_timer_start_time_clock);
end_time_display = (TextView) findViewById(R.id.create_timer_end_time_clock);
weekdays_toggle = (ToggleButton) findViewById(R.id.create_timer_weekdays_btn);
weekends_toggle = (ToggleButton) findViewById(R.id.create_timer_weekends_btn);
toggle_btn_days = new ArrayList<ToggleButton>();
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_sun));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_mon));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_tue));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_wed));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_thu));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_fri));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_sat));
colorPicked = getResources().getColor(R.color.colorPrimary);
done = (ImageButton) findViewById(R.id.add_timer_button);
}
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.create_timer);
initializeToolbar();
setupElements();
Bundle extras = getIntent().getExtras();
if (extras != null) {
bundledTimer = (TimerSession) extras.getSerializable("Timer");
initializeView(bundledTimer);
} else {
initializeView();
}
setupFunctionality();
}
// called via XML
public void onPaletteClick(MenuItem item) {
hideSoftKeyboard();
colorPicker.setOnColorSelectedListener(new ColorPickerSwatch.OnColorSelectedListener() {
@Override
public void onColorSelected(int color) {
colorPicked = color;
changeThemeColor(color);
changeButtonColors(color);
}
});
colorPicker.show(getFragmentManager(), COLOR_CAL_TAG);
}
private void initializeToolbar() {
toolbar = (Toolbar) findViewById(R.id.create_timer_toolbar);
toolbar.setTitle("New Timer");
toolbar.setNavigationIcon(R.drawable.ic_action_remove);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
toolbar.inflateMenu(R.menu.color_menu);
/* ColorPicker Menu */
String[] color_array = getBaseContext().getResources().getStringArray(R.array.default_color_choice_values);
int[] cArray = new int[color_array.length];
for (int k = 0; k < color_array.length; k++) {
cArray[k] = Color.parseColor(color_array[k]);
}
colorPicker = ColorPickerDialog.newInstance(R.string.color_picker_title, cArray, R.color.colorPrimary, 5, ColorPickerDialog.SIZE_SMALL);
}
// default (called when no bundledTimer is passed in)
public void initializeView() {
Calendar nextHour = Calendar.getInstance();
nextHour.add(Calendar.HOUR_OF_DAY, 1);
boolean[] default_days = new boolean[7];
default_days[getIntFromDayOfWeek(nextHour.get(Calendar.DAY_OF_WEEK))] = true;
initializeView("", TimerSession.TimerSessionType.VIBRATE, Calendar.getInstance(), nextHour, default_days);
}
public void initializeView(TimerSession t) {
bundledTimerDays = Arrays.copyOf(t.getDays(), 7);
colorPicked = t.getColor();
initializeView(t.getName(), t.getType(), t.getStartTime(), t.getEndTime(), bundledTimerDays);
}
// Apply values to UI elements
public void initializeView(String name, TimerSession.TimerSessionType type, Calendar start_time, Calendar end_time, boolean[] days) {
nameField.setText(name);
if(type == TimerSession.TimerSessionType.VIBRATE) {
markVibrateType(vibrate_toggle, true);
}
else {
markVibrateType(silent_toggle, true);
}
start_time_display.setText(generateTimeFromCalendar(start_time));
end_time_display.setText(generateTimeFromCalendar(end_time));
for(int i = 0; i < 7; i++){
if(days[i]) markDay(i, true);
else markDay(i, false);
}
checkDays();
changeButtonColors(colorPicked);
changeThemeColor(colorPicked);
}
// Attach listeners to UI elements
public void setupFunctionality() {
// vibrate and silent toggles cannot both be checked at the same time
vibrate_toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
hideSoftKeyboard();
markVibrateType(vibrate_toggle, true);
if(silent_toggle.isChecked()) {
markVibrateType(silent_toggle, false);
}
}
});
silent_toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
hideSoftKeyboard();
markVibrateType(silent_toggle, true);
if(vibrate_toggle.isChecked()) {
markVibrateType(vibrate_toggle, false);
}
}
});
// timePicker dialog should popup when tapping on start/end TextView
start_time_display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyboard();
String[] start = start_time_display.getText().toString().split(":");
int h = Integer.parseInt(start[0]);
int m = Integer.parseInt(start[1]);
showTimePickerDialog(h, m, START_TIME_TAG);
}
});
end_time_display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyboard();
String[] end = end_time_display.getText().toString().split(":");
int h = Integer.parseInt(end[0]);
int m = Integer.parseInt(end[1]);
showTimePickerDialog(h, m, END_TIME_TAG);
}
});
// circle days btn
// if sunday(0) OR saturday(6) is clicked
for(int i = 0; i < 7; i+=6){
final int finalI = i;
toggle_btn_days.get(i).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(toggle_btn_days.get(finalI).isChecked()) {
boolean_days[finalI] = true;
checkDays();
} else {
weekends_toggle.setChecked(false);
boolean_days[finalI] = false;
}
}
});
}
// if one of the toggle_btn_days from mon-fri is clicked
for(int i = 1; i < 6; i++){
final int finalI = i;
toggle_btn_days.get(i).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(toggle_btn_days.get(finalI).isChecked()) {
boolean_days[finalI] = true;
checkDays();
} else {
weekdays_toggle.setChecked(false);
boolean_days[finalI] = false;
}
}
});
}
// weekdays and weekends button
weekdays_toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyboard();
if(weekdays_toggle.isChecked()) {
for(int i = 1; i <= 5; i++)
markDay(i, true);
} else {
for(int i = 1; i <= 5; i++)
markDay(i, false);
}
}
});
weekends_toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyboard();
if(weekends_toggle.isChecked()) {
for(int i = 0; i < 7; i+=6)
markDay(i, true);
} else {
for(int i = 0; i < 7; i+=6)
markDay(i, false);
}
}
});
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TimerSession newTimer = produceNewTSObject();
// check if fields are valid
if(!checkValidity(newTimer)) return;
try {
if(bundledTimer != null) modifyTimer(newTimer);
else createTimerSession(newTimer);
} catch (TimerConflictException e) {
createDialog("Timer Conflict", "The time specified is in conflict with another timer. Please try again.");
}
}
});
}
// Rules:
// - cannot create a timer with an empty name
// - cannot create a timer that ends before it begins
// - cannot create a timer without a day
private boolean checkValidity(TimerSession newTimer) {
String name = newTimer.getName().trim();
if (name.equals("")) {
createDialog("Insufficient info", "Please specify a timer name.");
return false;
}
if (!newTimer.getStartTime().before(newTimer.getEndTime())) {
createDialog("Invalid Time Range", "Please specify a valid range.");
return false;
}
boolean[] days = newTimer.getDays();
for (int i = 0; i < 7; i++) {
if (days[i]) return true;
}
createDialog("Insufficient info", "Please specify a day.");
return false;
}
// Sum up the values on the interface and produce a new TimerSession object
private TimerSession produceNewTSObject() {
String name = nameField.getText().toString();
TimerSession.TimerSessionType type;
if(vibrate_toggle.isChecked()) type = TimerSession.TimerSessionType.VIBRATE;
else type = TimerSession.TimerSessionType.SILENT;
String[] temp = start_time_display.getText().toString().split(":");
int h = Integer.parseInt(temp[0]);
int m = Integer.parseInt(temp[1]);
Calendar startTime = generateCalendar(h,m);
temp = end_time_display.getText().toString().split(":");
h = Integer.parseInt(temp[0]);
m = Integer.parseInt(temp[1]);
Calendar endTime = generateCalendar(h,m);
return new TimerSession(name, type, startTime, endTime, boolean_days, colorPicked);
}
// Create a new timer unless it is in conflict with another existing timer
private void createTimerSession(TimerSession newTimer) throws TimerConflictException {
TimerSessionHolder timerSessionHolder = TimerSessionHolder.getInstance();
timerSessionHolder.addTimer(newTimer);
finish();
}
// Doesn't create a new system timer if only the name or color has been modified
private void modifyTimer(TimerSession newTimer) throws TimerConflictException {
TimerSessionHolder timerSessionHolder = TimerSessionHolder.getInstance();
int modify = isModified(newTimer);
switch(modify) {
case -1: // no new change has been made
break;
case 0: // minor change
TimerSession existingTimer = timerSessionHolder.getTimerById(bundledTimer.getId());
existingTimer.setName(newTimer.getName());
existingTimer.setColor(newTimer.getColor());
finish();
break;
case 1: // big change
newTimer.setActive(bundledTimer.getActive());
timerSessionHolder.updateTimer(newTimer, bundledTimer);
finish();
break;
}
}
//change weekdays + weekends button colors
private void changeButtonColors(int colorPicked) {
for(ToggleButton day : toggle_btn_days) {
if(day.isChecked()) {
changeButtonColor(day, colorPicked);
} else {
day.setChecked(true);
changeButtonColor(day, colorPicked);
day.setChecked(false);
}
}
if(weekdays_toggle.isChecked()) {
changeButtonColor(weekdays_toggle, colorPicked);
} else {
weekdays_toggle.setChecked(true);
changeButtonColor(weekdays_toggle, colorPicked);
weekdays_toggle.setChecked(false);
}
if(weekends_toggle.isChecked()) {
changeButtonColor(weekends_toggle, colorPicked);
} else {
weekends_toggle.setChecked(true);
changeButtonColor(weekends_toggle, colorPicked);
weekends_toggle.setChecked(false);
}
if(vibrate_toggle.isChecked()) vibrate_toggle.setTextColor(colorPicked);
else silent_toggle.setTextColor(colorPicked);
}
// change the color of the checked state of the ToggleButton
private void changeButtonColor(ToggleButton btn, int rgbColor) {
try {
StateListDrawable stateListDrawable = (StateListDrawable) btn.getBackground();
int[] currentState = btn.getBackground().getState();
Method getStateDrawable = StateListDrawable.class.getMethod("getStateDrawable", int.class);
Method getStateDrawableIndex = StateListDrawable.class.getMethod("getStateDrawableIndex", int[].class);
int index = (int) getStateDrawableIndex.invoke(stateListDrawable,currentState);
GradientDrawable drawable = (GradientDrawable) getStateDrawable.invoke(stateListDrawable,index);
drawable.setColor(rgbColor);
drawable.invalidateSelf();
} catch (Exception e) {
e.printStackTrace();
}
}
// change toolbar and status bar color
private void changeThemeColor(int color) {
//To darken the colorPicked
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.8f;
int colorPickedDarker = Color.HSVToColor(hsv);
//Changing Status Bar color
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(colorPickedDarker);
}
colorPicked = color;
toolbar.setBackgroundColor(color);
}
//to get rid of keyboard
private void hideSoftKeyboard() {
if (getCurrentFocus() != null && getCurrentFocus() instanceof EditText) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(nameField.getWindowToken(), 0);
}
}
// generate a calendar object on the current day with hour and minute
private Calendar generateCalendar(int hour, int minute) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
// create an alert dialog
private void createDialog(String title, String msg) {
if(dialog != null && dialog.isShowing()) dialog.dismiss();
dialog = new AlertDialog.Builder(this)
.setTitle(title)
.setIcon(R.drawable.ic_launcher)
.setMessage(msg)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).show();
}
// create a string in the format HH:mm from a calendar object
private String generateTimeFromCalendar(Calendar c) {
int hour = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
String hour_str = (hour < 10)? "0" + hour: Integer.toString(hour);
String min_str = (min < 10)? "0" + min: Integer.toString(min);
return hour_str + ":" + min_str;
}
// set boolean at index d to false and
// uncheck the toggle button on screen
private void markDay(int d, boolean b) {
boolean_days[d] = b;
toggle_btn_days.get(d).setChecked(b);
}
// set highlight to toggle btn text
// and set toggle btn to be checked
private void markVibrateType(ToggleButton btn, Boolean b) {
btn.setChecked(b);
if(b) btn.setTextColor(colorPicked); // checked
else btn.setTextColor(getResources().getColor(android.R.color.black)); // unchecked
}
// if Mon-Fri are checked, check the weekdays button
// if Sat,Sun are checked, check the weekends button
private void checkDays() {
weekdays_toggle.setChecked(true);
for(int i = 1; i <= 5; i++) {
if(!boolean_days[i]) {
weekdays_toggle.setChecked(false);
break;
}
}
weekends_toggle.setChecked(false);
if(boolean_days[0] && boolean_days[6]) weekends_toggle.setChecked(true);
}
// return 1 if modified
// return 0 if only color or name are modified
// return -1 if nothing is modified
private int isModified(TimerSession newTimer) {
if (!newTimer.getStartTime().equals(bundledTimer.getStartTime()) || !newTimer.getEndTime().equals(bundledTimer.getEndTime()) ||
!arrayCompare(newTimer.getDays(),bundledTimer.getDays()) || newTimer.getType() != bundledTimer.getType()){
System.out.println("RETURNING 1");
return 1;
} else if (newTimer.getColor() != bundledTimer.getColor() || !newTimer.getName().equals(bundledTimer.getName())) {
System.out.println("RETURNING 0");
return 0;
} else {
System.out.println("RETURNING -1");
return -1;
}
}
private boolean arrayCompare(boolean[] arr1, boolean[] arr2) {
for(int i = 0; i < arr1.length; i++) {
if(arr1[i] != arr2[i]) return false;
}
return true;
}
private void showTimePickerDialog(int h, int m, String tag) {
Bundle b = new Bundle();
b.putInt(KEY_HOUR, h);
b.putInt(KEY_MINUTE, m);
timePicker.setArguments(b);
timePicker.show(getSupportFragmentManager(), tag);
}
@Override
public void onTimeSet(TimePicker t, int h, int m) {
if(timePicker.getTag().equals(START_TIME_TAG)) {
start_time_display.setText(fixTimeFormat(h) + ":" + fixTimeFormat(m));
} else {
end_time_display.setText(fixTimeFormat(h) + ":" + fixTimeFormat(m));
}
}
// Given a time append 0 if needed
// eg. 1 -> 01
private String fixTimeFormat(int n) {
if(n < 10) return "0" + n;
else return Integer.toString(n);
}
private int getIntFromDayOfWeek(int DAY_OF_WEEK) {
switch(DAY_OF_WEEK) {
case Calendar.SUNDAY:
return 0;
case Calendar.MONDAY:
return 1;
case Calendar.TUESDAY:
return 2;
case Calendar.WEDNESDAY:
return 3;
case Calendar.THURSDAY:
return 4;
case Calendar.FRIDAY:
return 5;
case Calendar.SATURDAY:
return 6;
}
return -1;
}
// ONLY FOR DEBUGGING
private String printArray(boolean[] array) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < array.length; i++){
if(array[i]) sb.append("1 ");
else sb.append("0 ");
}
return sb.toString();
}
}
| Vibernate-2/src/main/java/com/napontaratan/vibernate/CreateTimerActivity.java | package com.napontaratan.vibernate;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.*;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.napontaratan.vibernate.model.TimerConflictException;
import com.napontaratan.vibernate.model.TimerSession;
import com.napontaratan.vibernate.model.TimerSessionHolder;
import com.napontaratan.vibernate.view.ColorPickerDialog;
import com.napontaratan.vibernate.view.ColorPickerSwatch;
import com.napontaratan.vibernate.view.CreateTimerTimePicker;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
public class CreateTimerActivity extends FragmentActivity implements TimePickerDialog.OnTimeSetListener {
private static String COLOR_CAL_TAG = "cal";
private static String START_TIME_TAG = "start";
private static String END_TIME_TAG = "end";
public static String KEY_HOUR = "hour";
public static String KEY_MINUTE = "minute";
// if modifying a timer, the information is passed through a bundle
private TimerSession bundledTimer;
private boolean[] bundledTimerDays; // used to compare if timer has changed
// ELEMENTS
private CreateTimerTimePicker timePicker;
private ColorPickerDialog colorPicker;
private Toolbar toolbar;
private Dialog dialog;
private EditText nameField;
private TextView start_time_display;
private TextView end_time_display;
private ToggleButton vibrate_toggle;
private ToggleButton silent_toggle;
private ToggleButton weekdays_toggle;
private ToggleButton weekends_toggle;
private List<ToggleButton> toggle_btn_days;
private boolean[] boolean_days = new boolean[7];
private ImageButton done;
// VALUES
private int colorPicked;
// @Override
// protected void onStart() {
// super.onStart();
// GoogleAnalytics.getInstance(this).reportActivityStart(this);
// }
//
// @Override
// protected void onStop() {
// super.onStop();
// GoogleAnalytics.getInstance(this).reportActivityStop(this);
// }
public void setupElements() {
nameField = (EditText) findViewById(R.id.create_timer_name_field);
nameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
nameField.clearFocus();
vibrate_toggle = (ToggleButton) findViewById(R.id.create_timer_type_vibrate);
silent_toggle = (ToggleButton) findViewById(R.id.create_timer_type_silent);
timePicker = new CreateTimerTimePicker();
start_time_display = (TextView) findViewById(R.id.create_timer_start_time_clock);
end_time_display = (TextView) findViewById(R.id.create_timer_end_time_clock);
weekdays_toggle = (ToggleButton) findViewById(R.id.create_timer_weekdays_btn);
weekends_toggle = (ToggleButton) findViewById(R.id.create_timer_weekends_btn);
toggle_btn_days = new ArrayList<ToggleButton>();
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_sun));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_mon));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_tue));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_wed));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_thu));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_fri));
toggle_btn_days.add((ToggleButton) findViewById(R.id.create_timer_sat));
colorPicked = getResources().getColor(R.color.colorPrimary);
done = (ImageButton) findViewById(R.id.add_timer_button);
}
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.create_timer);
initializeToolbar();
setupElements();
Bundle extras = getIntent().getExtras();
if (extras != null) {
bundledTimer = (TimerSession) extras.getSerializable("Timer");
initializeView(bundledTimer);
} else {
initializeView();
}
setupFunctionality();
}
// called via XML
public void onPaletteClick(MenuItem item) {
hideSoftKeyboard();
colorPicker.setOnColorSelectedListener(new ColorPickerSwatch.OnColorSelectedListener() {
@Override
public void onColorSelected(int color) {
colorPicked = color;
changeThemeColor(color);
changeButtonColors(color);
}
});
colorPicker.show(getFragmentManager(), COLOR_CAL_TAG);
}
private void initializeToolbar() {
toolbar = (Toolbar) findViewById(R.id.create_timer_toolbar);
toolbar.setTitle("New Timer");
toolbar.setNavigationIcon(R.drawable.ic_action_remove);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
toolbar.inflateMenu(R.menu.color_menu);
/* ColorPicker Menu */
String[] color_array = getBaseContext().getResources().getStringArray(R.array.default_color_choice_values);
int[] cArray = new int[color_array.length];
for (int k = 0; k < color_array.length; k++) {
cArray[k] = Color.parseColor(color_array[k]);
}
colorPicker = ColorPickerDialog.newInstance(R.string.color_picker_title, cArray, R.color.colorPrimary, 5, ColorPickerDialog.SIZE_SMALL);
}
// default (called when no bundledTimer is passed in)
public void initializeView() {
Calendar nextHour = Calendar.getInstance();
nextHour.add(Calendar.HOUR_OF_DAY, 1);
boolean[] default_days = new boolean[7];
default_days[getIntFromDayOfWeek(nextHour.get(Calendar.DAY_OF_WEEK))] = true;
initializeView("", TimerSession.TimerSessionType.VIBRATE, Calendar.getInstance(), nextHour, default_days, colorPicked);
}
public void initializeView(TimerSession t) {
bundledTimerDays = Arrays.copyOf(t.getDays(), 7);
initializeView(t.getName(), t.getType(), t.getStartTime(), t.getEndTime(), bundledTimerDays, t.getColor());
}
// Apply values to UI elements
public void initializeView(String name, TimerSession.TimerSessionType type, Calendar start_time, Calendar end_time, boolean[] days, int color) {
nameField.setText(name);
if(type == TimerSession.TimerSessionType.VIBRATE) {
vibrate_toggle.setChecked(true);
vibrate_toggle.setTextColor(color);
}
else {
silent_toggle.setChecked(true);
silent_toggle.setTextColor(color);
}
start_time_display.setText(generateTimeFromCalendar(start_time));
end_time_display.setText(generateTimeFromCalendar(end_time));
for(int i = 0; i < 7; i++){
if(days[i]) markDay(i, true);
else markDay(i, false);
}
checkDays();
changeButtonColors(color);
changeThemeColor(color);
}
// Attach listeners to UI elements
public void setupFunctionality() {
// vibrate and silent toggles cannot both be checked at the same time
vibrate_toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
hideSoftKeyboard();
if(silent_toggle.isChecked()) {
silent_toggle.setChecked(false);
silent_toggle.setTextColor(getResources().getColor(android.R.color.black));
}
if(!vibrate_toggle.isChecked()) {
vibrate_toggle.setChecked(true);
vibrate_toggle.setTextColor(colorPicked);
}
}
});
silent_toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
hideSoftKeyboard();
if(vibrate_toggle.isChecked()) {
vibrate_toggle.setChecked(false);
vibrate_toggle.setTextColor(getResources().getColor(android.R.color.black));
}
if(!silent_toggle.isChecked()) {
silent_toggle.setChecked(true);
silent_toggle.setTextColor(colorPicked);
}
}
});
// timePicker dialog should popup when tapping on start/end TextView
start_time_display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyboard();
String[] start = start_time_display.getText().toString().split(":");
int h = Integer.parseInt(start[0]);
int m = Integer.parseInt(start[1]);
showTimePickerDialog(h, m, START_TIME_TAG);
}
});
end_time_display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyboard();
String[] end = end_time_display.getText().toString().split(":");
int h = Integer.parseInt(end[0]);
int m = Integer.parseInt(end[1]);
showTimePickerDialog(h, m, END_TIME_TAG);
}
});
// circle days btn
// if sunday(0) OR saturday(6) is clicked
for(int i = 0; i < 7; i+=6){
final int finalI = i;
toggle_btn_days.get(i).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(toggle_btn_days.get(finalI).isChecked()) {
boolean_days[finalI] = true;
checkDays();
} else {
weekends_toggle.setChecked(false);
boolean_days[finalI] = false;
}
}
});
}
// if one of the toggle_btn_days from mon-fri is clicked
for(int i = 1; i < 6; i++){
final int finalI = i;
toggle_btn_days.get(i).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(toggle_btn_days.get(finalI).isChecked()) {
boolean_days[finalI] = true;
checkDays();
} else {
weekdays_toggle.setChecked(false);
boolean_days[finalI] = false;
}
}
});
}
// weekdays and weekends button
weekdays_toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyboard();
if(weekdays_toggle.isChecked()) {
for(int i = 1; i <= 5; i++)
markDay(i, true);
} else {
for(int i = 1; i <= 5; i++)
markDay(i, false);
}
}
});
weekends_toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyboard();
if(weekends_toggle.isChecked()) {
for(int i = 0; i < 7; i+=6)
markDay(i, true);
} else {
for(int i = 0; i < 7; i+=6)
markDay(i, false);
}
}
});
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TimerSession newTimer = produceNewTSObject();
// check if fields are valid
if(!checkValidity(newTimer)) return;
try {
if(bundledTimer != null) modifyTimer(newTimer);
else createTimerSession(newTimer);
} catch (TimerConflictException e) {
createDialog("Timer Conflict", "The time specified is in conflict with another timer. Please try again.");
}
}
});
}
// Rules:
// - cannot create a timer with an empty name
// - cannot create a timer that ends before it begins
// - cannot create a timer without a day
private boolean checkValidity(TimerSession newTimer) {
String name = newTimer.getName().trim();
if (name.equals("")) {
createDialog("Insufficient info", "Please specify a timer name.");
return false;
}
if (!newTimer.getStartTime().before(newTimer.getEndTime())) {
createDialog("Invalid Time Range", "Please specify a valid range.");
return false;
}
boolean[] days = newTimer.getDays();
for (int i = 0; i < 7; i++) {
if (days[i]) return true;
}
createDialog("Insufficient info", "Please specify a day.");
return false;
}
// Sum up the values on the interface and produce a new TimerSession object
private TimerSession produceNewTSObject() {
String name = nameField.getText().toString();
TimerSession.TimerSessionType type;
if(vibrate_toggle.isChecked()) type = TimerSession.TimerSessionType.VIBRATE;
else type = TimerSession.TimerSessionType.SILENT;
String[] temp = start_time_display.getText().toString().split(":");
int h = Integer.parseInt(temp[0]);
int m = Integer.parseInt(temp[1]);
Calendar startTime = generateCalendar(h,m);
temp = end_time_display.getText().toString().split(":");
h = Integer.parseInt(temp[0]);
m = Integer.parseInt(temp[1]);
Calendar endTime = generateCalendar(h,m);
return new TimerSession(name, type, startTime, endTime, boolean_days, colorPicked);
}
// Create a new timer unless it is in conflict with another existing timer
private void createTimerSession(TimerSession newTimer) throws TimerConflictException {
TimerSessionHolder timerSessionHolder = TimerSessionHolder.getInstance();
timerSessionHolder.addTimer(newTimer);
finish();
}
// Doesn't create a new system timer if only the name or color has been modified
private void modifyTimer(TimerSession newTimer) throws TimerConflictException {
TimerSessionHolder timerSessionHolder = TimerSessionHolder.getInstance();
int modify = isModified(newTimer);
switch(modify) {
case -1: // no new change has been made
break;
case 0: // minor change
TimerSession existingTimer = timerSessionHolder.getTimerById(bundledTimer.getId());
existingTimer.setName(newTimer.getName());
existingTimer.setColor(newTimer.getColor());
finish();
break;
case 1: // big change
newTimer.setActive(bundledTimer.getActive());
timerSessionHolder.updateTimer(newTimer, bundledTimer);
finish();
break;
}
}
//change weekdays + weekends button colors
private void changeButtonColors(int colorPicked) {
for(ToggleButton day : toggle_btn_days) {
if(day.isChecked()) {
changeButtonColor(day, colorPicked);
} else {
day.setChecked(true);
changeButtonColor(day, colorPicked);
day.setChecked(false);
}
}
if(weekdays_toggle.isChecked()) {
changeButtonColor(weekdays_toggle, colorPicked);
} else {
weekdays_toggle.setChecked(true);
changeButtonColor(weekdays_toggle, colorPicked);
weekdays_toggle.setChecked(false);
}
if(weekends_toggle.isChecked()) {
changeButtonColor(weekends_toggle, colorPicked);
} else {
weekends_toggle.setChecked(true);
changeButtonColor(weekends_toggle, colorPicked);
weekends_toggle.setChecked(false);
}
if(vibrate_toggle.isChecked()) vibrate_toggle.setTextColor(colorPicked);
else silent_toggle.setTextColor(colorPicked);
}
// change the color of the checked state of the ToggleButton
private void changeButtonColor(ToggleButton btn, int rgbColor) {
try {
StateListDrawable stateListDrawable = (StateListDrawable) btn.getBackground();
int[] currentState = btn.getBackground().getState();
Method getStateDrawable = StateListDrawable.class.getMethod("getStateDrawable", int.class);
Method getStateDrawableIndex = StateListDrawable.class.getMethod("getStateDrawableIndex", int[].class);
int index = (int) getStateDrawableIndex.invoke(stateListDrawable,currentState);
GradientDrawable drawable = (GradientDrawable) getStateDrawable.invoke(stateListDrawable,index);
drawable.setColor(rgbColor);
drawable.invalidateSelf();
} catch (Exception e) {
e.printStackTrace();
}
}
// change toolbar and status bar color
private void changeThemeColor(int color) {
//To darken the colorPicked
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.8f;
int colorPickedDarker = Color.HSVToColor(hsv);
//Changing Status Bar color
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(colorPickedDarker);
}
colorPicked = color;
toolbar.setBackgroundColor(color);
}
//to get rid of keyboard
private void hideSoftKeyboard() {
if (getCurrentFocus() != null && getCurrentFocus() instanceof EditText) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(nameField.getWindowToken(), 0);
}
}
// generate a calendar object on the current day with hour and minute
private Calendar generateCalendar(int hour, int minute) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
// create an alert dialog
private void createDialog(String title, String msg) {
if(dialog != null && dialog.isShowing()) dialog.dismiss();
dialog = new AlertDialog.Builder(this)
.setTitle(title)
.setIcon(R.drawable.ic_launcher)
.setMessage(msg)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).show();
}
// create a string in the format HH:mm from a calendar object
private String generateTimeFromCalendar(Calendar c) {
int hour = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
String hour_str = (hour < 10)? "0" + hour: Integer.toString(hour);
String min_str = (min < 10)? "0" + min: Integer.toString(min);
return hour_str + ":" + min_str;
}
// set boolean at index d to false and
// uncheck the toggle button on screen
private void markDay(int d, boolean b) {
boolean_days[d] = b;
toggle_btn_days.get(d).setChecked(b);
}
// if Mon-Fri are checked, check the weekdays button
// if Sat,Sun are checked, check the weekends button
private void checkDays() {
weekdays_toggle.setChecked(true);
for(int i = 1; i <= 5; i++) {
if(!boolean_days[i]) {
weekdays_toggle.setChecked(false);
break;
}
}
weekends_toggle.setChecked(false);
if(boolean_days[0] && boolean_days[6]) weekends_toggle.setChecked(true);
}
// return 1 if modified
// return 0 if only color or name are modified
// return -1 if nothing is modified
private int isModified(TimerSession newTimer) {
if (!newTimer.getStartTime().equals(bundledTimer.getStartTime()) || !newTimer.getEndTime().equals(bundledTimer.getEndTime()) ||
!arrayCompare(newTimer.getDays(),bundledTimer.getDays()) || newTimer.getType() != bundledTimer.getType()){
return 1;
} else if (newTimer.getColor() != bundledTimer.getColor() || !newTimer.getName().equals(bundledTimer.getName())) {
return 0;
} else {
return -1;
}
}
private boolean arrayCompare(boolean[] arr1, boolean[] arr2) {
for(int i = 0; i < arr1.length; i++) {
if(arr1[i] != arr2[i]) return false;
}
return true;
}
private void showTimePickerDialog(int h, int m, String tag) {
Bundle b = new Bundle();
b.putInt(KEY_HOUR, h);
b.putInt(KEY_MINUTE, m);
timePicker.setArguments(b);
timePicker.show(getSupportFragmentManager(), tag);
}
@Override
public void onTimeSet(TimePicker t, int h, int m) {
if(timePicker.getTag().equals(START_TIME_TAG)) {
start_time_display.setText(fixTimeFormat(h) + ":" + fixTimeFormat(m));
} else {
end_time_display.setText(fixTimeFormat(h) + ":" + fixTimeFormat(m));
}
}
// Given a time append 0 if needed
// eg. 1 -> 01
private String fixTimeFormat(int n) {
if(n < 10) return "0" + n;
else return Integer.toString(n);
}
private int getIntFromDayOfWeek(int DAY_OF_WEEK) {
switch(DAY_OF_WEEK) {
case Calendar.SUNDAY:
return 0;
case Calendar.MONDAY:
return 1;
case Calendar.TUESDAY:
return 2;
case Calendar.WEDNESDAY:
return 3;
case Calendar.THURSDAY:
return 4;
case Calendar.FRIDAY:
return 5;
case Calendar.SATURDAY:
return 6;
}
return -1;
}
// ONLY FOR DEBUGGING
private String printArray(boolean[] array) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < array.length; i++){
if(array[i]) sb.append("1 ");
else sb.append("0 ");
}
return sb.toString();
}
}
| Fixed #34
| Vibernate-2/src/main/java/com/napontaratan/vibernate/CreateTimerActivity.java | Fixed #34 | <ide><path>ibernate-2/src/main/java/com/napontaratan/vibernate/CreateTimerActivity.java
<ide> nextHour.add(Calendar.HOUR_OF_DAY, 1);
<ide> boolean[] default_days = new boolean[7];
<ide> default_days[getIntFromDayOfWeek(nextHour.get(Calendar.DAY_OF_WEEK))] = true;
<del> initializeView("", TimerSession.TimerSessionType.VIBRATE, Calendar.getInstance(), nextHour, default_days, colorPicked);
<add> initializeView("", TimerSession.TimerSessionType.VIBRATE, Calendar.getInstance(), nextHour, default_days);
<ide> }
<ide>
<ide> public void initializeView(TimerSession t) {
<ide> bundledTimerDays = Arrays.copyOf(t.getDays(), 7);
<del> initializeView(t.getName(), t.getType(), t.getStartTime(), t.getEndTime(), bundledTimerDays, t.getColor());
<add> colorPicked = t.getColor();
<add> initializeView(t.getName(), t.getType(), t.getStartTime(), t.getEndTime(), bundledTimerDays);
<ide> }
<ide>
<ide> // Apply values to UI elements
<del> public void initializeView(String name, TimerSession.TimerSessionType type, Calendar start_time, Calendar end_time, boolean[] days, int color) {
<add> public void initializeView(String name, TimerSession.TimerSessionType type, Calendar start_time, Calendar end_time, boolean[] days) {
<ide> nameField.setText(name);
<ide> if(type == TimerSession.TimerSessionType.VIBRATE) {
<del> vibrate_toggle.setChecked(true);
<del> vibrate_toggle.setTextColor(color);
<add> markVibrateType(vibrate_toggle, true);
<ide> }
<ide> else {
<del> silent_toggle.setChecked(true);
<del> silent_toggle.setTextColor(color);
<add> markVibrateType(silent_toggle, true);
<ide> }
<ide>
<ide> start_time_display.setText(generateTimeFromCalendar(start_time));
<ide> }
<ide>
<ide> checkDays();
<del> changeButtonColors(color);
<del> changeThemeColor(color);
<add> changeButtonColors(colorPicked);
<add> changeThemeColor(colorPicked);
<ide> }
<ide>
<ide> // Attach listeners to UI elements
<ide> @Override
<ide> public void onClick(View view) {
<ide> hideSoftKeyboard();
<add> markVibrateType(vibrate_toggle, true);
<ide> if(silent_toggle.isChecked()) {
<del> silent_toggle.setChecked(false);
<del> silent_toggle.setTextColor(getResources().getColor(android.R.color.black));
<del> }
<del> if(!vibrate_toggle.isChecked()) {
<del> vibrate_toggle.setChecked(true);
<del> vibrate_toggle.setTextColor(colorPicked);
<add> markVibrateType(silent_toggle, false);
<ide> }
<ide> }
<ide> });
<ide> @Override
<ide> public void onClick(View view) {
<ide> hideSoftKeyboard();
<add> markVibrateType(silent_toggle, true);
<ide> if(vibrate_toggle.isChecked()) {
<del> vibrate_toggle.setChecked(false);
<del> vibrate_toggle.setTextColor(getResources().getColor(android.R.color.black));
<del> }
<del> if(!silent_toggle.isChecked()) {
<del> silent_toggle.setChecked(true);
<del> silent_toggle.setTextColor(colorPicked);
<add> markVibrateType(vibrate_toggle, false);
<ide> }
<ide> }
<ide> });
<ide> toggle_btn_days.get(d).setChecked(b);
<ide> }
<ide>
<add> // set highlight to toggle btn text
<add> // and set toggle btn to be checked
<add> private void markVibrateType(ToggleButton btn, Boolean b) {
<add> btn.setChecked(b);
<add> if(b) btn.setTextColor(colorPicked); // checked
<add> else btn.setTextColor(getResources().getColor(android.R.color.black)); // unchecked
<add> }
<add>
<ide> // if Mon-Fri are checked, check the weekdays button
<ide> // if Sat,Sun are checked, check the weekends button
<ide> private void checkDays() {
<ide> private int isModified(TimerSession newTimer) {
<ide> if (!newTimer.getStartTime().equals(bundledTimer.getStartTime()) || !newTimer.getEndTime().equals(bundledTimer.getEndTime()) ||
<ide> !arrayCompare(newTimer.getDays(),bundledTimer.getDays()) || newTimer.getType() != bundledTimer.getType()){
<add> System.out.println("RETURNING 1");
<ide> return 1;
<ide> } else if (newTimer.getColor() != bundledTimer.getColor() || !newTimer.getName().equals(bundledTimer.getName())) {
<add> System.out.println("RETURNING 0");
<ide> return 0;
<ide> } else {
<add> System.out.println("RETURNING -1");
<ide> return -1;
<ide> }
<ide> } |
|
Java | apache-2.0 | 72b47ac550f052b4f7303cdd362d150503ac7147 | 0 | cloudfoundry/cf-java-client,cloudfoundry/cf-java-client,alexander071/cf-java-client,orange-cloudfoundry/cf-java-client,Orange-OpenSource/cf-java-client,alexander071/cf-java-client,orange-cloudfoundry/cf-java-client,Orange-OpenSource/cf-java-client,cloudfoundry/cf-java-client | /*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry;
import org.cloudfoundry.client.CloudFoundryClient;
import org.cloudfoundry.client.v2.applications.ApplicationResource;
import org.cloudfoundry.client.v2.applications.DeleteApplicationRequest;
import org.cloudfoundry.client.v2.applications.ListApplicationsRequest;
import org.cloudfoundry.client.v2.domains.DeleteDomainRequest;
import org.cloudfoundry.client.v2.domains.DomainResource;
import org.cloudfoundry.client.v2.domains.ListDomainsRequest;
import org.cloudfoundry.client.v2.organizations.DeleteOrganizationRequest;
import org.cloudfoundry.client.v2.organizations.ListOrganizationsRequest;
import org.cloudfoundry.client.v2.organizations.OrganizationResource;
import org.cloudfoundry.client.v2.privatedomains.DeletePrivateDomainRequest;
import org.cloudfoundry.client.v2.privatedomains.ListPrivateDomainsRequest;
import org.cloudfoundry.client.v2.privatedomains.PrivateDomainResource;
import org.cloudfoundry.client.v2.routes.DeleteRouteRequest;
import org.cloudfoundry.client.v2.routes.ListRoutesRequest;
import org.cloudfoundry.client.v2.routes.RouteResource;
import org.cloudfoundry.client.v2.spaces.DeleteSpaceRequest;
import org.cloudfoundry.client.v2.spaces.ListSpacesRequest;
import org.cloudfoundry.client.v2.spaces.SpaceResource;
import org.cloudfoundry.util.JobUtils;
import org.cloudfoundry.util.PaginationUtils;
import org.cloudfoundry.util.ResourceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import static org.cloudfoundry.util.tuple.TupleUtils.function;
final class CloudFoundryCleaner {
private final Logger logger = LoggerFactory.getLogger("cloudfoundry-client.test");
private final CloudFoundryClient cloudFoundryClient;
private final Mono<Optional<String>> protectedDomainId;
private final Mono<Optional<String>> protectedOrganizationId;
private final Mono<List<String>> protectedSpaceIds;
CloudFoundryCleaner(CloudFoundryClient cloudFoundryClient, Mono<Optional<String>> protectedDomainId, Mono<Optional<String>> protectedOrganizationId, Mono<List<String>> protectedSpaceIds) {
this.cloudFoundryClient = cloudFoundryClient;
this.protectedDomainId = protectedDomainId;
this.protectedOrganizationId = protectedOrganizationId;
this.protectedSpaceIds = protectedSpaceIds;
}
void clean() {
Mono
.when(this.protectedDomainId, this.protectedOrganizationId, this.protectedSpaceIds)
.flatMap(function((protectedDomainId, protectedOrganizationId, protectedSpaceIds) -> {
Predicate<ApplicationResource> applicationPredicate = protectedOrganizationId
.map(id -> (Predicate<ApplicationResource>) r -> !protectedSpaceIds.contains(ResourceUtils.getEntity(r).getSpaceId()))
.orElse(r -> true);
Predicate<OrganizationResource> organizationPredicate = protectedOrganizationId
.map(id -> (Predicate<OrganizationResource>) r -> !ResourceUtils.getId(r).equals(id))
.orElse(r -> true);
Predicate<DomainResource> domainPredicate = protectedDomainId
.map(id -> (Predicate<DomainResource>) r -> !ResourceUtils.getId(r).equals(id))
.orElse(r -> true);
Predicate<PrivateDomainResource> privateDomainPredicate = r -> true;
Predicate<RouteResource> routePredicate = r -> true;
Predicate<SpaceResource> spacePredicate = protectedOrganizationId
.map(id -> (Predicate<SpaceResource>) r -> !ResourceUtils.getEntity(r).getOrganizationId().equals(id))
.orElse(r -> true);
return cleanApplications(this.cloudFoundryClient, applicationPredicate)
.after(() -> cleanRoutes(this.cloudFoundryClient, routePredicate))
.after(() -> cleanDomains(this.cloudFoundryClient, domainPredicate))
.after(() -> cleanPrivateDomains(this.cloudFoundryClient, privateDomainPredicate))
.after(() -> cleanSpaces(this.cloudFoundryClient, spacePredicate))
.after(() -> cleanOrganizations(this.cloudFoundryClient, organizationPredicate));
}))
.doOnSubscribe(s -> this.logger.debug(">> CLEANUP <<"))
.doOnError(Throwable::printStackTrace)
.doOnComplete(() -> this.logger.debug("<< CLEANUP >>"))
.after()
.get(Duration.ofMinutes(5));
}
private static Flux<Void> cleanApplications(CloudFoundryClient cloudFoundryClient, Predicate<ApplicationResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.applicationsV2()
.list(ListApplicationsRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(applicationId -> cloudFoundryClient.applicationsV2()
.delete(DeleteApplicationRequest.builder()
.applicationId(applicationId)
.build()));
}
private static Flux<Void> cleanDomains(CloudFoundryClient cloudFoundryClient, Predicate<DomainResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.domains()
.list(ListDomainsRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(domainId -> cloudFoundryClient.domains()
.delete(DeleteDomainRequest.builder()
.async(true)
.domainId(domainId)
.build()))
.map(ResourceUtils::getId)
.flatMap(jobId -> JobUtils.waitForCompletion(cloudFoundryClient, jobId));
}
private static Flux<Void> cleanOrganizations(CloudFoundryClient cloudFoundryClient, Predicate<OrganizationResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.organizations()
.list(ListOrganizationsRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(organizationId -> cloudFoundryClient.organizations()
.delete(DeleteOrganizationRequest.builder()
.async(true)
.organizationId(organizationId)
.build()))
.map(ResourceUtils::getId)
.flatMap(jobId -> JobUtils.waitForCompletion(cloudFoundryClient, jobId));
}
private static Flux<Void> cleanPrivateDomains(CloudFoundryClient cloudFoundryClient, Predicate<PrivateDomainResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.privateDomains()
.list(ListPrivateDomainsRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(privateDomainId -> cloudFoundryClient.privateDomains()
.delete(DeletePrivateDomainRequest.builder()
.async(true)
.privateDomainId(privateDomainId)
.build()))
.map(ResourceUtils::getId)
.flatMap(jobId -> JobUtils.waitForCompletion(cloudFoundryClient, jobId));
}
private static Flux<Void> cleanRoutes(CloudFoundryClient cloudFoundryClient, Predicate<RouteResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.routes()
.list(ListRoutesRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(routeId -> cloudFoundryClient.routes()
.delete(DeleteRouteRequest.builder()
.async(true)
.routeId(routeId)
.build()))
.map(ResourceUtils::getId)
.flatMap(jobId -> JobUtils.waitForCompletion(cloudFoundryClient, jobId));
}
private static Flux<Void> cleanSpaces(CloudFoundryClient cloudFoundryClient, Predicate<SpaceResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.spaces()
.list(ListSpacesRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(spaceId -> cloudFoundryClient.spaces()
.delete(DeleteSpaceRequest.builder()
.async(true)
.spaceId(spaceId)
.build()))
.map(ResourceUtils::getId)
.flatMap(jobId -> JobUtils.waitForCompletion(cloudFoundryClient, jobId));
}
}
| integration-test/src/test/java/org/cloudfoundry/CloudFoundryCleaner.java | /*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry;
import org.cloudfoundry.client.CloudFoundryClient;
import org.cloudfoundry.client.v2.applications.ApplicationResource;
import org.cloudfoundry.client.v2.applications.DeleteApplicationRequest;
import org.cloudfoundry.client.v2.applications.ListApplicationsRequest;
import org.cloudfoundry.client.v2.domains.DeleteDomainRequest;
import org.cloudfoundry.client.v2.domains.DomainResource;
import org.cloudfoundry.client.v2.domains.ListDomainsRequest;
import org.cloudfoundry.client.v2.organizations.DeleteOrganizationRequest;
import org.cloudfoundry.client.v2.organizations.ListOrganizationsRequest;
import org.cloudfoundry.client.v2.organizations.OrganizationResource;
import org.cloudfoundry.client.v2.privatedomains.DeletePrivateDomainRequest;
import org.cloudfoundry.client.v2.privatedomains.ListPrivateDomainsRequest;
import org.cloudfoundry.client.v2.privatedomains.PrivateDomainResource;
import org.cloudfoundry.client.v2.routes.DeleteRouteRequest;
import org.cloudfoundry.client.v2.routes.ListRoutesRequest;
import org.cloudfoundry.client.v2.routes.RouteResource;
import org.cloudfoundry.client.v2.spaces.DeleteSpaceRequest;
import org.cloudfoundry.client.v2.spaces.ListSpacesRequest;
import org.cloudfoundry.client.v2.spaces.SpaceResource;
import org.cloudfoundry.util.JobUtils;
import org.cloudfoundry.util.PaginationUtils;
import org.cloudfoundry.util.ResourceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import static org.cloudfoundry.util.tuple.TupleUtils.function;
final class CloudFoundryCleaner {
private final Logger logger = LoggerFactory.getLogger("cloudfoundry-client.test");
private final CloudFoundryClient cloudFoundryClient;
private final Mono<Optional<String>> protectedDomainId;
private final Mono<Optional<String>> protectedOrganizationId;
private final Mono<List<String>> protectedSpaceIds;
CloudFoundryCleaner(CloudFoundryClient cloudFoundryClient, Mono<Optional<String>> protectedDomainId, Mono<Optional<String>> protectedOrganizationId, Mono<List<String>> protectedSpaceIds) {
this.cloudFoundryClient = cloudFoundryClient;
this.protectedDomainId = protectedDomainId;
this.protectedOrganizationId = protectedOrganizationId;
this.protectedSpaceIds = protectedSpaceIds;
}
void clean() {
Mono
.when(this.protectedDomainId, this.protectedOrganizationId, this.protectedSpaceIds)
.flatMap(function((protectedDomainId, protectedOrganizationId, protectedSpaceIds) -> {
Predicate<ApplicationResource> applicationPredicate = protectedOrganizationId
.map(id -> (Predicate<ApplicationResource>) r -> !protectedSpaceIds.contains(ResourceUtils.getEntity(r).getSpaceId()))
.orElse(r -> true);
Predicate<OrganizationResource> organizationPredicate = protectedOrganizationId
.map(id -> (Predicate<OrganizationResource>) r -> !ResourceUtils.getId(r).equals(id))
.orElse(r -> true);
Predicate<DomainResource> domainPredicate = protectedDomainId
.map(id -> (Predicate<DomainResource>) r -> !ResourceUtils.getId(r).equals(id))
.orElse(r -> true);
Predicate<PrivateDomainResource> privateDomainPredicate = r -> true;
Predicate<RouteResource> routePredicate = r -> true;
Predicate<SpaceResource> spacePredicate = protectedOrganizationId
.map(id -> (Predicate<SpaceResource>) r -> !ResourceUtils.getEntity(r).getOrganizationId().equals(id))
.orElse(r -> true);
return cleanApplications(this.cloudFoundryClient, applicationPredicate)
.after(() -> cleanRoutes(this.cloudFoundryClient, routePredicate))
.after(() -> cleanDomains(this.cloudFoundryClient, domainPredicate))
.after(() -> cleanPrivateDomains(this.cloudFoundryClient, privateDomainPredicate))
.after(() -> cleanSpaces(this.cloudFoundryClient, spacePredicate))
.after(() -> cleanOrganizations(this.cloudFoundryClient, organizationPredicate));
}))
.doOnSubscribe(s -> this.logger.debug(">> CLEANUP <<"))
.doOnError(Throwable::printStackTrace)
.doOnComplete(() -> this.logger.debug("<< CLEANUP >>"))
.after()
.get(Duration.ofMinutes(10));
}
private static Flux<Void> cleanApplications(CloudFoundryClient cloudFoundryClient, Predicate<ApplicationResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.applicationsV2()
.list(ListApplicationsRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(applicationId -> cloudFoundryClient.applicationsV2()
.delete(DeleteApplicationRequest.builder()
.applicationId(applicationId)
.build()));
}
private static Flux<Void> cleanDomains(CloudFoundryClient cloudFoundryClient, Predicate<DomainResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.domains()
.list(ListDomainsRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(domainId -> cloudFoundryClient.domains()
.delete(DeleteDomainRequest.builder()
.async(true)
.domainId(domainId)
.build()))
.map(ResourceUtils::getId)
.flatMap(jobId -> JobUtils.waitForCompletion(cloudFoundryClient, jobId));
}
private static Flux<Void> cleanOrganizations(CloudFoundryClient cloudFoundryClient, Predicate<OrganizationResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.organizations()
.list(ListOrganizationsRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(organizationId -> cloudFoundryClient.organizations()
.delete(DeleteOrganizationRequest.builder()
.async(true)
.organizationId(organizationId)
.build()))
.map(ResourceUtils::getId)
.flatMap(jobId -> JobUtils.waitForCompletion(cloudFoundryClient, jobId));
}
private static Flux<Void> cleanPrivateDomains(CloudFoundryClient cloudFoundryClient, Predicate<PrivateDomainResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.privateDomains()
.list(ListPrivateDomainsRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(privateDomainId -> cloudFoundryClient.privateDomains()
.delete(DeletePrivateDomainRequest.builder()
.async(true)
.privateDomainId(privateDomainId)
.build()))
.map(ResourceUtils::getId)
.flatMap(jobId -> JobUtils.waitForCompletion(cloudFoundryClient, jobId));
}
private static Flux<Void> cleanRoutes(CloudFoundryClient cloudFoundryClient, Predicate<RouteResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.routes()
.list(ListRoutesRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(routeId -> cloudFoundryClient.routes()
.delete(DeleteRouteRequest.builder()
.async(true)
.routeId(routeId)
.build()))
.map(ResourceUtils::getId)
.flatMap(jobId -> JobUtils.waitForCompletion(cloudFoundryClient, jobId));
}
private static Flux<Void> cleanSpaces(CloudFoundryClient cloudFoundryClient, Predicate<SpaceResource> predicate) {
return PaginationUtils
.requestResources(page -> cloudFoundryClient.spaces()
.list(ListSpacesRequest.builder()
.page(page)
.build()))
.filter(predicate)
.map(ResourceUtils::getId)
.flatMap(spaceId -> cloudFoundryClient.spaces()
.delete(DeleteSpaceRequest.builder()
.async(true)
.spaceId(spaceId)
.build()))
.map(ResourceUtils::getId)
.flatMap(jobId -> JobUtils.waitForCompletion(cloudFoundryClient, jobId));
}
}
| Revert "Extend cleanup timeout"
This reverts commit f09a1d78e5dbcc675a453cf75cf311a9a5449317.
| integration-test/src/test/java/org/cloudfoundry/CloudFoundryCleaner.java | Revert "Extend cleanup timeout" | <ide><path>ntegration-test/src/test/java/org/cloudfoundry/CloudFoundryCleaner.java
<ide> .doOnError(Throwable::printStackTrace)
<ide> .doOnComplete(() -> this.logger.debug("<< CLEANUP >>"))
<ide> .after()
<del> .get(Duration.ofMinutes(10));
<add> .get(Duration.ofMinutes(5));
<ide> }
<ide>
<ide> private static Flux<Void> cleanApplications(CloudFoundryClient cloudFoundryClient, Predicate<ApplicationResource> predicate) { |
|
JavaScript | mit | 129704dd3bdf8e9403957cc1acbe0ab0373da9e7 | 0 | groonga/gcs,groonga/gcs | var nativeNroonga = require('nroonga');
var nroonga = require('../wrapped-nroonga');
var IndexField = require('./index-field').IndexField;
exports.MINIMUM_DOMAIN_NAME_LENGTH = 3;
exports.MAXIMUM_DOMAIN_NAME_LENGTH = 28;
exports.INVALID_DOMAIN_NAME_CHARACTER_PATTERN = /[^\-a-z0-9]/g;
exports.INVALID_TABLE_NAME_CHARACTER_PATTERN = /[^_a-z0-9]/g;
function assertValidDomainName(domain) {
if (typeof domain != 'string')
throw new Error('domain name must be a string');
if (domain.length < exports.MINIMUM_DOMAIN_NAME_LENGTH)
throw new Error('too short domain name (minimum length = ' +
exports.MINIMUM_DOMAIN_NAME_LENGTH + ')');
if (domain.length > exports.MAXIMUM_DOMAIN_NAME_LENGTH)
throw new Error('too long domain name (max length = ' +
exports.MAXIMUM_DOMAIN_NAME_LENGTH + ')');
var invalidCharacter = domain.match(exports.INVALID_DOMAIN_NAME_CHARACTER_PATTERN) ||
domain.match(exports.INVALID_TABLE_NAME_CHARACTER_PATTERN);
if (invalidCharacter) {
var characters = Array.prototype.map.call(invalidCharacter, function(aCharacter) {
return '"' + aCharacter + '"';
});
throw new Error(characters.join(', ') + ' cannot appear in a domain name');
}
}
// Accepts two arguments: source and context.
// You can give them in the reversed order, like:
// new Domain("source", context) or new Domain(context, "source")
function Domain() {
var source, context;
for (var i = 0, maxi = arguments.length, argument; i < maxi; i++) {
argument = arguments[i];
if (!argument) continue;
if (argument instanceof nroonga.Context ||
argument instanceof nativeNroonga.Database) {
context = argument;
} else if (argument) {
source = argument;
}
}
if (source instanceof Domain)
return source;
this.initialize(source, context);
}
Domain.prototype = {
initialize: function(source, context) {
this.context = new nroonga.Context(context);
this.name = this.getName(source);
this.indexFields = {};
// for validation
this.tableName;
this.termsTableName;
},
getName: function(source) {
if (typeof source == 'string')
return source;
if (source.query && source.query.DomainName)
return source.query.DomainName;
if (source.headers && source.headers.host) {
var host = source.headers.host;
var domainNameFromHost = Domain.getNameFromHost(host);
if (domainNameFromHost)
return domainNameFromHost;
}
if (source.url) {
var domainNameFromPath = Domain.getNameFromPath(source.url);
if (domainNameFromPath)
return domainNameFromPath;
}
throw new Error('no domain name');
},
get tableName() {
if (!this._tableName) {
assertValidDomainName(this.name);
this._tableName = this.name;
}
return this._tableName;
},
get termsTableName() {
if (!this._termsTableName)
this._termsTableName = this.tableName + '_BigramTerms';
return this._termsTableName;
},
getIndexField: function(field) {
return this.indexFields[field] ||
(this.indexFields[field] = new IndexField(field, this));
},
get indexFields() {
if (!this.context)
throw new Error('no context');
var columns = this.context.ordinalColumnsSync(this.tableName);
var fields = columns.map(this.columnToIndexField, this);
return fields;
},
columnToIndexField: function(column) {
// XXX The "name" must be the field name given by the user,
// not normalized. Because there is no such information in the
// context and currently the column name is luckly equals to the
// given field name, we can use the column name.
var name = column.name;
var field = this.getIndexField(name);
var type;
if (column.type == 'var') {
if (column.range == nroonga.ShortText)
type = 'text';
} else if (column.type == 'fix') {
if (column.range == nroonga.UInt32)
type = 'uint';
else if (column.range == field.alterTableName)
type = 'literal';
}
if (!type)
throw new Error('unknown unfixed column '+column.name);
field.type = type;
return field;
},
get synonymTableName() {
if (!this._synonymTableName)
this._synonymTableName = this.tableName + '_synonyms';
return this._synonymTableName;
}
};
exports.Domain = Domain;
Domain.getNameFromHost = function(host) {
var domainMatcher = /^(?:doc|search)-([^\.]+)-([^\.\-]+)\./;
var match = host.match(domainMatcher);
if (match)
return match[1];
return '';
};
Domain.getNameFromPath = function(path) {
var domainMatcher = /^\/gcs\/([^\/]+)/;
var match = path.match(domainMatcher);
if (match)
return match[1];
return '';
};
| lib/database/domain.js | var nativeNroonga = require('nroonga');
var nroonga = require('../wrapped-nroonga');
var IndexField = require('./index-field').IndexField;
exports.MINIMUM_DOMAIN_NAME_LENGTH = 3;
exports.MAXIMUM_DOMAIN_NAME_LENGTH = 28;
exports.INVALID_DOMAIN_NAME_CHARACTER_PATTERN = /[^\-a-z0-9]/g;
exports.INVALID_TABLE_NAME_CHARACTER_PATTERN = /[^_a-z0-9]/g;
function assertValidDomainName(domain) {
if (typeof domain != 'string')
throw new Error('domain name must be a string');
if (domain.length < exports.MINIMUM_DOMAIN_NAME_LENGTH)
throw new Error('too short domain name (minimum length = ' +
exports.MINIMUM_DOMAIN_NAME_LENGTH + ')');
if (domain.length > exports.MAXIMUM_DOMAIN_NAME_LENGTH)
throw new Error('too long domain name (max length = ' +
exports.MAXIMUM_DOMAIN_NAME_LENGTH + ')');
var invalidCharacter = domain.match(exports.INVALID_DOMAIN_NAME_CHARACTER_PATTERN) ||
domain.match(exports.INVALID_TABLE_NAME_CHARACTER_PATTERN);
if (invalidCharacter) {
var characters = Array.prototype.map.call(invalidCharacter, function(aCharacter) {
return '"' + aCharacter + '"';
});
throw new Error(characters.join(', ') + ' cannot appear in a domain name');
}
}
// Accepts two arguments: source and context.
// You can give them in the reversed order, like:
// new Domain("source", context) or new Domain(context, "source")
function Domain() {
var source, context;
for (var i = 0, maxi = arguments.length, argument; i < maxi; i++) {
argument = arguments[i];
if (!argument) continue;
if (argument instanceof nroonga.Context ||
argument instanceof nativeNroonga.Database) {
context = argument;
} else if (argument) {
source = argument;
}
}
if (source instanceof Domain)
return source;
this.initialize(source, context);
}
Domain.prototype = {
initialize: function(source, context) {
this.context = context;
this.name = this.getName(source);
this.indexFields = {};
// for validation
this.tableName;
this.termsTableName;
},
getName: function(source) {
if (typeof source == 'string')
return source;
if (source.query && source.query.DomainName)
return source.query.DomainName;
if (source.headers && source.headers.host) {
var host = source.headers.host;
var domainNameFromHost = Domain.getNameFromHost(host);
if (domainNameFromHost)
return domainNameFromHost;
}
if (source.url) {
var domainNameFromPath = Domain.getNameFromPath(source.url);
if (domainNameFromPath)
return domainNameFromPath;
}
throw new Error('no domain name');
},
get tableName() {
if (!this._tableName) {
assertValidDomainName(this.name);
this._tableName = this.name;
}
return this._tableName;
},
get termsTableName() {
if (!this._termsTableName)
this._termsTableName = this.tableName + '_BigramTerms';
return this._termsTableName;
},
getIndexField: function(field) {
return this.indexFields[field] ||
(this.indexFields[field] = new IndexField(field, this));
},
get indexFields() {
if (!this.context)
throw new Error('no context');
var columns = this.context.ordinalColumnsSync(this.tableName);
var fields = columns.map(this.columnToIndexField, this);
return fields;
},
columnToIndexField: function(column) {
// XXX The "name" must be the field name given by the user,
// not normalized. Because there is no such information in the
// context and currently the column name is luckly equals to the
// given field name, we can use the column name.
var name = column.name;
var field = this.getIndexField(name);
var type;
if (column.type == 'var') {
if (column.range == nroonga.ShortText)
type = 'text';
} else if (column.type == 'fix') {
if (column.range == nroonga.UInt32)
type = 'uint';
else if (column.range == field.alterTableName)
type = 'literal';
}
if (!type)
throw new Error('unknown unfixed column '+column.name);
field.type = type;
return field;
},
get synonymTableName() {
if (!this._synonymTableName)
this._synonymTableName = this.tableName + '_synonyms';
return this._synonymTableName;
}
};
exports.Domain = Domain;
Domain.getNameFromHost = function(host) {
var domainMatcher = /^(?:doc|search)-([^\.]+)-([^\.\-]+)\./;
var match = host.match(domainMatcher);
if (match)
return match[1];
return '';
};
Domain.getNameFromPath = function(path) {
var domainMatcher = /^\/gcs\/([^\/]+)/;
var match = path.match(domainMatcher);
if (match)
return match[1];
return '';
};
| Use wrapped context always
| lib/database/domain.js | Use wrapped context always | <ide><path>ib/database/domain.js
<ide> }
<ide> Domain.prototype = {
<ide> initialize: function(source, context) {
<del> this.context = context;
<add> this.context = new nroonga.Context(context);
<ide> this.name = this.getName(source);
<ide> this.indexFields = {};
<ide> // for validation |
|
Java | agpl-3.0 | 8f3ac08cfdc008823fede5441cebd98c95408720 | 0 | kuali/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,kuali/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,quikkian-ua-devops/kfs,kuali/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,kuali/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,bhutchinson/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,bhutchinson/kfs,bhutchinson/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,kkronenb/kfs,kuali/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,smith750/kfs | /*
* Copyright 2008 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.cab.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.kfs.coa.businessobject.ObjectCode;
import org.kuali.kfs.fp.businessobject.CapitalAssetInformation;
import org.kuali.kfs.fp.businessobject.CapitalAssetInformationDetail;
import org.kuali.kfs.fp.document.CashReceiptDocument;
import org.kuali.kfs.fp.document.DistributionOfIncomeAndExpenseDocument;
import org.kuali.kfs.fp.document.GeneralErrorCorrectionDocument;
import org.kuali.kfs.fp.document.InternalBillingDocument;
import org.kuali.kfs.fp.document.ProcurementCardDocument;
import org.kuali.kfs.fp.document.ServiceBillingDocument;
import org.kuali.kfs.fp.document.YearEndDistributionOfIncomeAndExpenseDocument;
import org.kuali.kfs.fp.document.YearEndGeneralErrorCorrectionDocument;
import org.kuali.kfs.integration.cab.CapitalAssetBuilderAssetTransactionType;
import org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService;
import org.kuali.kfs.integration.cam.CapitalAssetManagementModuleService;
import org.kuali.kfs.integration.purap.CapitalAssetLocation;
import org.kuali.kfs.integration.purap.CapitalAssetSystem;
import org.kuali.kfs.integration.purap.ExternalPurApItem;
import org.kuali.kfs.integration.purap.ItemCapitalAsset;
import org.kuali.kfs.integration.purap.PurchasingAccountsPayableModuleService;
import org.kuali.kfs.module.cab.CabConstants;
import org.kuali.kfs.module.cab.CabKeyConstants;
import org.kuali.kfs.module.cab.CabParameterConstants;
import org.kuali.kfs.module.cab.CabPropertyConstants;
import org.kuali.kfs.module.cab.businessobject.AssetTransactionType;
import org.kuali.kfs.module.cab.businessobject.GeneralLedgerEntry;
import org.kuali.kfs.module.cab.businessobject.GeneralLedgerEntryAsset;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableDocument;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableItemAsset;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableLineAssetAccount;
import org.kuali.kfs.module.cab.document.service.PurApInfoService;
import org.kuali.kfs.module.cam.CamsConstants;
import org.kuali.kfs.module.cam.CamsKeyConstants;
import org.kuali.kfs.module.cam.CamsPropertyConstants;
import org.kuali.kfs.module.cam.CamsConstants.DocumentTypeName;
import org.kuali.kfs.module.cam.businessobject.Asset;
import org.kuali.kfs.module.cam.businessobject.AssetGlobal;
import org.kuali.kfs.module.cam.businessobject.AssetGlobalDetail;
import org.kuali.kfs.module.cam.businessobject.AssetPaymentAssetDetail;
import org.kuali.kfs.module.cam.businessobject.AssetType;
import org.kuali.kfs.module.cam.document.service.AssetService;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.PurapKeyConstants;
import org.kuali.kfs.module.purap.PurapParameterConstants;
import org.kuali.kfs.module.purap.PurapPropertyConstants;
import org.kuali.kfs.module.purap.businessobject.AccountsPayableItem;
import org.kuali.kfs.module.purap.businessobject.AvailabilityMatrix;
import org.kuali.kfs.module.purap.businessobject.PurApAccountingLine;
import org.kuali.kfs.module.purap.businessobject.PurApItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingCapitalAssetItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingItemBase;
import org.kuali.kfs.module.purap.businessobject.PurchasingItemCapitalAssetBase;
import org.kuali.kfs.module.purap.document.AccountsPayableDocument;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.module.purap.document.PurchasingDocument;
import org.kuali.kfs.module.purap.document.RequisitionDocument;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.businessobject.AccountingLine;
import org.kuali.kfs.sys.businessobject.Building;
import org.kuali.kfs.sys.businessobject.Room;
import org.kuali.kfs.sys.businessobject.SourceAccountingLine;
import org.kuali.kfs.sys.businessobject.TargetAccountingLine;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.AccountingDocument;
import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
import org.kuali.rice.kns.bo.Campus;
import org.kuali.rice.kns.bo.DocumentHeader;
import org.kuali.rice.kns.bo.Parameter;
import org.kuali.rice.kns.datadictionary.AttributeDefinition;
import org.kuali.rice.kns.datadictionary.BusinessObjectEntry;
import org.kuali.rice.kns.service.BusinessObjectDictionaryService;
import org.kuali.rice.kns.service.BusinessObjectService;
import org.kuali.rice.kns.service.DataDictionaryService;
import org.kuali.rice.kns.service.DictionaryValidationService;
import org.kuali.rice.kns.service.KualiConfigurationService;
import org.kuali.rice.kns.service.KualiModuleService;
import org.kuali.rice.kns.service.ParameterService;
import org.kuali.rice.kns.util.GlobalVariables;
import org.kuali.rice.kns.util.KualiDecimal;
import org.kuali.rice.kns.util.ObjectUtils;
import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument;
public class CapitalAssetBuilderModuleServiceImpl implements CapitalAssetBuilderModuleService {
private static Logger LOG = Logger.getLogger(CapitalAssetBuilderModuleService.class);
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#getAllAssetTransactionTypes()
*/
public List<CapitalAssetBuilderAssetTransactionType> getAllAssetTransactionTypes() {
Class<? extends CapitalAssetBuilderAssetTransactionType> assetTransactionTypeClass = this.getKualiModuleService().getResponsibleModuleService(CapitalAssetBuilderAssetTransactionType.class).getExternalizableBusinessObjectImplementation(CapitalAssetBuilderAssetTransactionType.class);
return (List<CapitalAssetBuilderAssetTransactionType>) this.getBusinessObjectService().findAll(assetTransactionTypeClass);
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#validatePurchasingAccountsPayableData(org.kuali.kfs.sys.document.AccountingDocument)
*/
public boolean validatePurchasingData(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
String documentType = (purchasingDocument instanceof RequisitionDocument) ? "REQUISITION" : "PURCHASE_ORDER";
if (PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateIndividualCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
else if (PurapConstants.CapitalAssetSystemTypes.ONE_SYSTEM.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateOneSystemCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetSystems(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
else if (PurapConstants.CapitalAssetSystemTypes.MULTIPLE.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateMultipleSystemsCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetSystems(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
return false;
}
public boolean validateAccountsPayableData(AccountingDocument accountingDocument) {
AccountsPayableDocument apDocument = (AccountsPayableDocument) accountingDocument;
boolean valid = true;
for (PurApItem purApItem : apDocument.getItems()) {
AccountsPayableItem accountsPayableItem = (AccountsPayableItem) purApItem;
// only run on ap items that were line items (not additional charge items) and were cams items
if ((!accountsPayableItem.getItemType().isAdditionalChargeIndicator()) && StringUtils.isNotEmpty(accountsPayableItem.getCapitalAssetTransactionTypeCode())) {
valid &= validateAccountsPayableItem(accountsPayableItem);
}
}
return valid;
}
/**
* Perform the item level capital asset validation to determine if the given document is not allowed to become an Automatic
* Purchase Order (APO). The APO is not allowed if any accounting strings on the document are using an object level indicated as
* capital via a parameter setting.
*/
public boolean doesAccountingLineFailAutomaticPurchaseOrderRules(AccountingLine accountingLine) {
PurApAccountingLine purapAccountingLine = (PurApAccountingLine) accountingLine;
purapAccountingLine.refreshNonUpdateableReferences();
return getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.CAPITAL_ASSET_OBJECT_LEVELS, purapAccountingLine.getObjectCode().getFinancialObjectLevelCode()).evaluationSucceeds();
}
/**
* Perform the document level capital asset validation to determine if the given document is not allowed to become an Automatic
* Purchase Order (APO). The APO is not allowed if any capital asset items exist on the document.
*/
public boolean doesDocumentFailAutomaticPurchaseOrderRules(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
return ObjectUtils.isNotNull(purchasingDocument.getPurchasingCapitalAssetItems()) && !purchasingDocument.getPurchasingCapitalAssetItems().isEmpty();
}
public boolean validateAutomaticPurchaseOrderRule(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
for (PurApItem item : purchasingDocument.getItems()) {
if (doesItemNeedCapitalAsset(item.getItemTypeCode(), item.getSourceAccountingLines())) {
// if the item needs capital asset, we cannot have an APO, so return false.
return false;
}
}
return true;
}
public boolean doesItemNeedCapitalAsset(String itemTypeCode, List accountingLines) {
if (PurapConstants.ItemTypeCodes.ITEM_TYPE_TRADE_IN_CODE.equals(itemTypeCode)) {
// FIXME: Chris - this should be true but need to look to see where itemline number is referenced first
// return true;
return false;
}// else
for (Iterator iterator = accountingLines.iterator(); iterator.hasNext();) {
PurApAccountingLine accountingLine = (PurApAccountingLine) iterator.next();
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
if (ObjectUtils.isNotNull(accountingLine.getObjectCode()) && isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
return true;
}
}
return false;
}
public boolean validateUpdateCAMSView(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
boolean valid = true;
for (PurApItem purapItem : purchasingDocument.getItems()) {
if (purapItem.getItemType().isLineItemIndicator()) {
if (!doesItemNeedCapitalAsset(purapItem.getItemTypeCode(), purapItem.getSourceAccountingLines())) {
PurchasingCapitalAssetItem camsItem = ((PurchasingItem) purapItem).getPurchasingCapitalAssetItem();
if (camsItem != null && !camsItem.isEmpty()) {
valid = false;
GlobalVariables.getErrorMap().putError("newPurchasingItemCapitalAssetLine", PurapKeyConstants.ERROR_CAPITAL_ASSET_ITEM_NOT_CAMS_ELIGIBLE, "in line item # " + purapItem.getItemLineNumber());
}
}
}
}
return valid;
}
public boolean validateAddItemCapitalAssetBusinessRules(ItemCapitalAsset asset) {
boolean valid = true;
if (asset.getCapitalAssetNumber() == null) {
valid = false;
}
else {
valid = SpringContext.getBean(DictionaryValidationService.class).isBusinessObjectValid((PurchasingItemCapitalAssetBase) asset);
}
if (!valid) {
String propertyName = "newPurchasingItemCapitalAssetLine." + PurapPropertyConstants.CAPITAL_ASSET_NUMBER;
String errorKey = PurapKeyConstants.ERROR_CAPITAL_ASSET_ASSET_NUMBER_MUST_BE_LONG_NOT_NULL;
GlobalVariables.getErrorMap().putError(propertyName, errorKey);
}
return valid;
}
public boolean warningObjectLevelCapital(AccountingDocument accountingDocument) {
org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument purapDocument = (org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument) accountingDocument;
for (PurApItem item : purapDocument.getItems()) {
if (item.getItemType().isLineItemIndicator() && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
List<PurApAccountingLine> accounts = item.getSourceAccountingLines();
BigDecimal unitPrice = item.getItemUnitPrice();
String itemIdentifier = item.getItemIdentifierString();
for (PurApAccountingLine account : accounts) {
ObjectCode objectCode = account.getObjectCode();
if (!validateLevelCapitalAssetIndication(unitPrice, objectCode, itemIdentifier)) {
// found an error
return false;
}
}
}
}
// no need for error
return true;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for individual system type. This also
* calls validations for quantity on locations equal quantity on line items, validates that the transaction type allows asset
* number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateIndividualCapitalAssetSystemFromPurchasing(String systemState, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
// For Individual Asset system type, the List of CapitalAssetSystems in the input parameter for
// validateAllFieldRequirementsByChart
// should be null. So we'll pass in a null here.
boolean valid = validateAllFieldRequirementsByChart(systemState, null, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL);
valid &= validateQuantityOnLocationsEqualsQuantityOnItem(capitalAssetItems, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL, systemState);
valid &= validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers(capitalAssetItems);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for one system type. This also calls
* validations that the transaction type allows asset number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateOneSystemCapitalAssetSystemFromPurchasing(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
boolean valid = validateAllFieldRequirementsByChart(systemState, capitalAssetSystems, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.ONE_SYSTEM);
String capitalAssetTransactionType = capitalAssetItems.get(0).getCapitalAssetTransactionTypeCode();
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[0].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetSystems.get(0), capitalAssetTransactionType, prefix);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for multiple system type. This also calls
* validations that the transaction type allows asset number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateMultipleSystemsCapitalAssetSystemFromPurchasing(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
boolean valid = validateAllFieldRequirementsByChart(systemState, capitalAssetSystems, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.MULTIPLE);
String capitalAssetTransactionType = capitalAssetItems.get(0).getCapitalAssetTransactionTypeCode();
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[0].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetSystems.get(0), capitalAssetTransactionType, prefix);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates all the field requirements by chart. It obtains a List of parameters where the parameter names are like
* "CHARTS_REQUIRING%" then loop through these parameters. If the system type is individual then invoke the
* validateFieldRequirementByChartForIndividualSystemType for further validation, otherwise invoke the
* validateFieldRequirementByChartForOneOrMultipleSystemType for further validation.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @param systemType
* @return
*/
protected boolean validateAllFieldRequirementsByChart(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType, String systemType) {
boolean valid = true;
List<Parameter> results = new ArrayList<Parameter>();
Map<String, String> criteria = new HashMap<String, String>();
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAMESPACE_CODE, CabConstants.Parameters.NAMESPACE);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_DETAIL_TYPE_CODE, CabConstants.Parameters.DETAIL_TYPE_DOCUMENT);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAME, "CHARTS_REQUIRING%" + documentType);
results.addAll(SpringContext.getBean(ParameterService.class).retrieveParametersGivenLookupCriteria(criteria));
for (Parameter parameter : results) {
if (ObjectUtils.isNotNull(parameter)) {
if (systemType.equals(PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL)) {
valid &= validateFieldRequirementByChartForIndividualSystemType(systemState, capitalAssetItems, chartCode, parameter.getParameterName(), parameter.getParameterValue());
}
else {
valid &= validateFieldRequirementByChartForOneOrMultipleSystemType(systemType, systemState, capitalAssetSystems, capitalAssetItems, chartCode, parameter.getParameterName(), parameter.getParameterValue());
}
}
}
return valid;
}
/**
* Validates all the field requirements by chart. It obtains a List of parameters where the parameter names are like
* "CHARTS_REQUIRING%" then loop through these parameters. If any of the parameter's values is null, then return false
*
* @param accountingDocument
* @return
*/
public boolean validateAllFieldRequirementsByChart(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
String documentType = (purchasingDocument instanceof RequisitionDocument) ? "REQUISITION" : "PURCHASE_ORDER";
boolean valid = true;
List<Parameter> results = new ArrayList<Parameter>();
Map<String,String> criteria = new HashMap<String,String>();
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAMESPACE_CODE, CabConstants.Parameters.NAMESPACE);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_DETAIL_TYPE_CODE, CabConstants.Parameters.DETAIL_TYPE_DOCUMENT);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAME, "CHARTS_REQUIRING%" + documentType);
results.addAll(SpringContext.getBean(ParameterService.class).retrieveParametersGivenLookupCriteria(criteria));
for (Parameter parameter : results) {
if (ObjectUtils.isNotNull(parameter)) {
if (parameter.getParameterValue() != null){
return false;
}
}
}
return valid;
}
/**
* Validates for PURCHASING_OBJECT_SUB_TYPES parameter. If at least one object code of any accounting line entered is of this
* type, then return false.
*
* @param accountingDocument
* @return
*/
public boolean validatePurchasingObjectSubType(AccountingDocument accountingDocument) {
boolean valid = true;
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
for (PurApItem item : purchasingDocument.getItems()) {
String itemTypeCode = item.getItemTypeCode();
List accountingLines = item.getSourceAccountingLines();
for (Iterator iterator = accountingLines.iterator(); iterator.hasNext();) {
PurApAccountingLine accountingLine = (PurApAccountingLine) iterator.next();
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
if (ObjectUtils.isNotNull(accountingLine.getObjectCode()) && isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
return false;
}
}
}
return valid;
}
/**
* Validates field requirement by chart for one or multiple system types.
*
* @param systemType
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param parameterName
* @param parameterValueString
* @return
*/
protected boolean validateFieldRequirementByChartForOneOrMultipleSystemType(String systemType, String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String parameterName, String parameterValueString) {
boolean valid = true;
boolean needValidation = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, parameterName, chartCode).evaluationSucceeds());
if (needValidation) {
if (parameterName.startsWith("CHARTS_REQUIRING_LOCATIONS_ADDRESS")) {
return validateCapitalAssetLocationAddressFieldsOneOrMultipleSystemType(capitalAssetSystems);
}
String mappedName = PurapConstants.CAMS_REQUIREDNESS_FIELDS.REQUIREDNESS_FIELDS_BY_PARAMETER_NAMES.get(parameterName);
if (mappedName != null) {
// Check the availability matrix here, if this field doesn't exist according to the avail. matrix, then no need
// to validate any further.
String availableValue = getValueFromAvailabilityMatrix(mappedName, systemType, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
return true;
}
// capitalAssetTransactionType field is off the item
if (mappedName.equals(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE)) {
String[] mappedNames = { PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS, mappedName };
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
valid &= validateFieldRequirementByChartHelper(item, ArrayUtils.subarray(mappedNames, 1, mappedNames.length), keyBuffer, item.getPurchasingItem().getItemLineNumber());
}
}
// all the other fields are off the system.
else {
List<String> mappedNamesList = new ArrayList<String>();
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS);
if (mappedName.indexOf(".") < 0) {
mappedNamesList.add(mappedName);
}
else {
mappedNamesList.addAll(mappedNameSplitter(mappedName));
}
// For One system type, we would only have 1 CapitalAssetSystem, however, for multiple we may have more than
// one systems in the future. Either way, this for loop should allow both the one system and multiple system
// types to work fine.
int count = 0;
for (CapitalAssetSystem system : capitalAssetSystems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[" + new Integer(count) + "].");
valid &= validateFieldRequirementByChartHelper(system, ArrayUtils.subarray(mappedNamesList.toArray(), 1, mappedNamesList.size()), keyBuffer, null);
count++;
}
}
}
}
return valid;
}
/**
* Validates the field requirement by chart for individual system type.
*
* @param systemState
* @param capitalAssetItems
* @param chartCode
* @param parameterName
* @param parameterValueString
* @return
*/
protected boolean validateFieldRequirementByChartForIndividualSystemType(String systemState, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String parameterName, String parameterValueString) {
boolean valid = true;
boolean needValidation = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, parameterName, chartCode).evaluationSucceeds());
if (needValidation) {
if (parameterName.startsWith("CHARTS_REQUIRING_LOCATIONS_ADDRESS")) {
return validateCapitalAssetLocationAddressFieldsForIndividualSystemType(capitalAssetItems);
}
String mappedName = PurapConstants.CAMS_REQUIREDNESS_FIELDS.REQUIREDNESS_FIELDS_BY_PARAMETER_NAMES.get(parameterName);
if (mappedName != null) {
// Check the availability matrix here, if this field doesn't exist according to the avail. matrix, then no need
// to validate any further.
String availableValue = getValueFromAvailabilityMatrix(mappedName, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
return true;
}
// capitalAssetTransactionType field is off the item
List<String> mappedNamesList = new ArrayList<String>();
if (mappedName.equals(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE)) {
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS);
mappedNamesList.add(mappedName);
}
// all the other fields are off the system which is off the item
else {
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS);
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEM);
if (mappedName.indexOf(".") < 0) {
mappedNamesList.add(mappedName);
}
else {
mappedNamesList.addAll(mappedNameSplitter(mappedName));
}
}
// For Individual system type, we'll always iterate through the item, then if the field is off the system, we'll get
// it through
// the purchasingCapitalAssetSystem of the item.
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
valid &= validateFieldRequirementByChartHelper(item, ArrayUtils.subarray(mappedNamesList.toArray(), 1, mappedNamesList.size()), keyBuffer, item.getPurchasingItem().getItemLineNumber());
}
}
}
return valid;
}
/**
* Utility method to split a long String using the "." as the delimiter then add each of the array element into a List of String
* and return the List of String.
*
* @param mappedName The String to be splitted.
* @return The List of String after being splitted, with the "." as delimiter.
*/
protected List<String> mappedNameSplitter(String mappedName) {
List<String> result = new ArrayList<String>();
String[] mappedNamesArray = mappedName.split("\\.");
for (int i = 0; i < mappedNamesArray.length; i++) {
result.add(mappedNamesArray[i]);
}
return result;
}
/**
* Validates the field requirement by chart recursively and give error messages when it returns false.
*
* @param bean The object to be used to obtain the property value
* @param mappedNames The array of Strings which when combined together, they form the field property
* @param errorKey The error key to be used for adding error messages to the error map.
* @param itemNumber The Integer that represents the item number that we're currently iterating.
* @return true if it passes the validation.
*/
protected boolean validateFieldRequirementByChartHelper(Object bean, Object[] mappedNames, StringBuffer errorKey, Integer itemNumber) {
boolean valid = true;
Object value = ObjectUtils.getPropertyValue(bean, (String) mappedNames[0]);
if (ObjectUtils.isNull(value)) {
errorKey.append(mappedNames[0]);
String fieldName = SpringContext.getBean(DataDictionaryService.class).getAttributeErrorLabel(bean.getClass(), (String) mappedNames[0]);
if (itemNumber != null) {
fieldName = fieldName + " in Item " + itemNumber;
}
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, fieldName);
return false;
}
else if (value instanceof Collection) {
if (((Collection) value).isEmpty()) {
// if this collection doesn't contain anything, when it's supposed to contain some strings with values, return
// false.
errorKey.append(mappedNames[0]);
String mappedNameStr = (String)mappedNames[0];
String methodToInvoke = "get" + (mappedNameStr.substring(0, 1)).toUpperCase() + mappedNameStr.substring(1, mappedNameStr.length()-1) + "Class";
Class offendingClass;
try {
offendingClass = (Class)bean.getClass().getMethod(methodToInvoke, null).invoke(bean, null);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
BusinessObjectEntry boe = SpringContext.getBean(DataDictionaryService.class).getDataDictionary().getBusinessObjectEntry(offendingClass.getSimpleName());
List<AttributeDefinition> offendingAttributes = boe.getAttributes();
AttributeDefinition offendingAttribute = offendingAttributes.get(0);
String fieldName = SpringContext.getBean(DataDictionaryService.class).getAttributeShortLabel(offendingClass, offendingAttribute.getName());
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, fieldName);
return false;
}
int count = 0;
for (Iterator iter = ((Collection) value).iterator(); iter.hasNext();) {
errorKey.append(mappedNames[0] + "[" + count + "].");
count++;
valid &= validateFieldRequirementByChartHelper(iter.next(), ArrayUtils.subarray(mappedNames, 1, mappedNames.length), errorKey, itemNumber);
}
return valid;
}
else if (StringUtils.isBlank(value.toString())) {
errorKey.append(mappedNames[0]);
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, (String) mappedNames[0]);
return false;
}
else if (mappedNames.length > 1) {
// this means we have not reached the end of a single field to be traversed yet, so continue with the recursion.
errorKey.append(mappedNames[0]).append(".");
valid &= validateFieldRequirementByChartHelper(value, ArrayUtils.subarray(mappedNames, 1, mappedNames.length), errorKey, itemNumber);
return valid;
}
else {
return true;
}
}
protected String getValueFromAvailabilityMatrix(String fieldName, String systemType, String systemState) {
for (AvailabilityMatrix am : PurapConstants.CAMS_AVAILABILITY_MATRIX.MATRIX_LIST) {
if (am.fieldName.equals(fieldName) && am.systemState.equals(systemState) && am.systemType.equals(systemType)) {
return am.availableValue;
}
}
// if we can't find any matching from availability matrix, return null for now.
return null;
}
/**
* Validates that the total quantity on all locations equals to the quantity on the line item. This is only used for IND system
* type.
*
* @param capitalAssetItems
* @return true if the total quantity on all locations equals to the quantity on the line item.
*/
protected boolean validateQuantityOnLocationsEqualsQuantityOnItem(List<PurchasingCapitalAssetItem> capitalAssetItems, String systemType, String systemState) {
boolean valid = true;
String availableValue = getValueFromAvailabilityMatrix(PurapPropertyConstants.CAPITAL_ASSET_LOCATIONS + "." + PurapPropertyConstants.QUANTITY, systemType, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
// If the location quantity isn't available on the document given the system type and system state, we don't need to
// validate this, just return true.
return true;
}
int count = 0;
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
if (item.getPurchasingItem() != null && item.getPurchasingItem().getItemType().isQuantityBasedGeneralLedgerIndicator() && !item.getPurchasingCapitalAssetSystem().getCapitalAssetLocations().isEmpty()) {
KualiDecimal total = new KualiDecimal(0);
for (CapitalAssetLocation location : item.getPurchasingCapitalAssetSystem().getCapitalAssetLocations()) {
if (ObjectUtils.isNotNull(location.getItemQuantity())) {
total = total.add(location.getItemQuantity());
}
}
if (!item.getPurchasingItem().getItemQuantity().equals(total)) {
valid = false;
String errorKey = PurapKeyConstants.ERROR_CAPITAL_ASSET_LOCATIONS_QUANTITY_MUST_EQUAL_ITEM_QUANTITY;
String propertyName = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "]." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEM + ".newPurchasingCapitalAssetLocationLine." + PurapPropertyConstants.QUANTITY;
GlobalVariables.getErrorMap().putError(propertyName, errorKey, Integer.toString(count + 1));
}
}
count++;
}
return valid;
}
/**
* Validates for the individual system type that for each of the items, the capitalAssetTransactionTypeCode matches the system
* parameter PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS, the method will return true but if it doesn't match the
* system parameter, then loop through each of the itemCapitalAssets. If there is any non-null capitalAssetNumber then return
* false.
*
* @param capitalAssetItems the List of PurchasingCapitalAssetItems on the document to be validated
* @return false if the capital asset transaction type does not match the system parameter that allows asset numbers but the
* itemCapitalAsset contains at least one asset numbers.
*/
protected boolean validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
int count = 0;
for (PurchasingCapitalAssetItem capitalAssetItem : capitalAssetItems) {
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetItem.getPurchasingCapitalAssetSystem(), capitalAssetItem.getCapitalAssetTransactionTypeCode(), prefix);
count++;
}
return valid;
}
/**
* Generic validation that if the capitalAssetTransactionTypeCode does not match the system parameter
* PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS and at least one of the itemCapitalAssets contain a non-null
* capitalAssetNumber then return false. This method is used by one system and multiple system types as well as being used as a
* helper method for validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers method.
*
* @param capitalAssetSystem the capitalAssetSystem containing a List of itemCapitalAssets to be validated.
* @param capitalAssetTransactionType the capitalAssetTransactionTypeCode containing asset numbers to be validated.
* @return false if the capital asset transaction type does not match the system parameter that allows asset numbers but the
* itemCapitalAsset contains at least one asset numbers.
*/
protected boolean validatePurchasingTransactionTypesAllowingAssetNumbers(CapitalAssetSystem capitalAssetSystem, String capitalAssetTransactionType, String prefix) {
boolean allowedAssetNumbers = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS, capitalAssetTransactionType).evaluationSucceeds());
if (allowedAssetNumbers) {
// If this is a transaction type that allows asset numbers, we don't need to validate anymore, just return true here.
return true;
}
else {
for (ItemCapitalAsset asset : capitalAssetSystem.getItemCapitalAssets()) {
if (asset.getCapitalAssetNumber() != null) {
String propertyName = prefix + PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE;
GlobalVariables.getErrorMap().putError(propertyName, PurapKeyConstants.ERROR_CAPITAL_ASSET_ASSET_NUMBERS_NOT_ALLOWED_TRANS_TYPE, capitalAssetTransactionType);
return false;
}
}
}
return true;
}
/**
* TODO: rename this method removing trade in reference? Validates that if the non quantity drive allowed indicator on the
* capital asset transaction type is false and the item is of non quantity type
*
* @param capitalAssetItems The List of PurchasingCapitalAssetItem to be validated.
* @return false if the indicator is false and there is at least one non quantity items on the list.
*/
protected boolean validateNonQuantityDrivenAllowedIndicatorAndTradeIn(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
int count = 0;
for (PurchasingCapitalAssetItem capitalAssetItem : capitalAssetItems) {
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "].";
if (StringUtils.isNotBlank(capitalAssetItem.getCapitalAssetTransactionTypeCode())) {
// ((PurchasingCapitalAssetItemBase)
// capitalAssetItem).refreshReferenceObject(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE);
if (!capitalAssetItem.getCapitalAssetTransactionType().getCapitalAssetNonquantityDrivenAllowIndicator()) {
if (!capitalAssetItem.getPurchasingItem().getItemType().isQuantityBasedGeneralLedgerIndicator()) {
String propertyName = prefix + PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE;
GlobalVariables.getErrorMap().putError(propertyName, PurapKeyConstants.ERROR_CAPITAL_ASSET_TRANS_TYPE_NOT_ALLOWING_NON_QUANTITY_ITEMS, capitalAssetItem.getCapitalAssetTransactionTypeCode());
valid &= false;
}
}
}
count++;
}
return valid;
}
/**
* Wrapper to do Capital Asset validations, generating errors instead of warnings. Makes sure that the given item's data
* relevant to its later possible classification as a Capital Asset is internally consistent, by marshaling and calling the
* methods marked as Capital Asset validations. This implementation assumes that all object codes are valid (real) object codes.
*
* @param recurringPaymentType The item's document's RecurringPaymentType
* @param item A PurchasingItemBase object
* @param apoCheck True if this check is for APO purposes
* @return True if the item passes all Capital Asset validations
*/
public boolean validateItemCapitalAssetWithErrors(String recurringPaymentTypeCode, ExternalPurApItem item, boolean apoCheck) {
PurchasingItemBase purchasingItem = (PurchasingItemBase) item;
List<String> previousErrorPath = GlobalVariables.getErrorMap().getErrorPath();
GlobalVariables.getErrorMap().clearErrorPath();
GlobalVariables.getErrorMap().addToErrorPath(PurapConstants.CAPITAL_ASSET_TAB_ERRORS);
boolean result = validatePurchasingItemCapitalAsset(recurringPaymentTypeCode, purchasingItem);
// Now that we're done with cams related validations, reset the error path to what it was previously.
GlobalVariables.getErrorMap().clearErrorPath();
for (String path : previousErrorPath) {
GlobalVariables.getErrorMap().addToErrorPath(path);
}
return result;
}
/**
* Makes sure that the given item's data relevant to its later possible classification as a Capital Asset is internally
* consistent, by marshaling and calling the methods marked as Capital Asset validations. This implementation assumes that all
* object codes are valid (real) object codes.
*
* @param recurringPaymentType The item's document's RecurringPaymentType
* @param item A PurchasingItemBase object
* @param warn A boolean which should be set to true if warnings are to be set on the calling document for most of the
* validations, rather than errors.
* @return True if the item passes all Capital Asset validations
*/
protected boolean validatePurchasingItemCapitalAsset(String recurringPaymentTypeCode, PurchasingItem item) {
boolean valid = true;
String capitalAssetTransactionTypeCode = "";
AssetTransactionType capitalAssetTransactionType = null;
String itemIdentifier = item.getItemIdentifierString();
if (item.getPurchasingCapitalAssetItem() != null) {
capitalAssetTransactionTypeCode = item.getPurchasingCapitalAssetItem().getCapitalAssetTransactionTypeCode();
// ((PurchasingCapitalAssetItemBase)
// item.getPurchasingCapitalAssetItem()).refreshReferenceObject(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE);
capitalAssetTransactionType = (AssetTransactionType) item.getPurchasingCapitalAssetItem().getCapitalAssetTransactionType();
}
// These checks do not depend on Accounting Line information, but do depend on transaction type.
if (!StringUtils.isEmpty(capitalAssetTransactionTypeCode)) {
valid &= validateCapitalAssetTransactionTypeVersusRecurrence(capitalAssetTransactionType, recurringPaymentTypeCode, itemIdentifier);
}
return valid &= validatePurapItemCapitalAsset(item, capitalAssetTransactionType);
}
/**
* This method validated purapItem giving a transtype
*
* @param recurringPaymentType
* @param item
* @param warn
* @return
*/
protected boolean validatePurapItemCapitalAsset(PurApItem item, AssetTransactionType capitalAssetTransactionType) {
boolean valid = true;
String itemIdentifier = item.getItemIdentifierString();
boolean quantityBased = item.getItemType().isQuantityBasedGeneralLedgerIndicator();
BigDecimal itemUnitPrice = item.getItemUnitPrice();
HashSet<String> capitalOrExpenseSet = new HashSet<String>(); // For the first validation on every accounting line.
// Do the checks that depend on Accounting Line information.
for (PurApAccountingLine accountingLine : item.getSourceAccountingLines()) {
// Because of ObjectCodeCurrent, we had to refresh this.
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
ObjectCode objectCode = accountingLine.getObjectCode();
if(ObjectUtils.isNotNull(objectCode)){
String capitalOrExpense = objectCodeCapitalOrExpense(objectCode);
capitalOrExpenseSet.add(capitalOrExpense); // HashSets accumulate distinct values (and nulls) only.
valid &= validateAccountingLinesNotCapitalAndExpense(capitalOrExpenseSet, itemIdentifier, objectCode);
// Do the checks involving capital asset transaction type.
if (capitalAssetTransactionType != null) {
valid &= validateObjectCodeVersusTransactionType(objectCode, capitalAssetTransactionType, itemIdentifier, quantityBased);
}
}
}
return valid;
}
/**
* Capital Asset validation: An item cannot have among its associated accounting lines both object codes that indicate it is a
* Capital Asset, and object codes that indicate that the item is not a Capital Asset. Whether an object code indicates that the
* item is a Capital Asset is determined by whether its level is among a specific set of levels that are deemed acceptable for
* such items.
*
* @param capitalOrExpenseSet A HashSet containing the distinct values of either "Capital" or "Expense" that have been added to
* it.
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier A String identifying the item for error display
* @param objectCode An ObjectCode, for error display
* @return True if the given HashSet contains at most one of either "Capital" or "Expense"
*/
protected boolean validateAccountingLinesNotCapitalAndExpense(HashSet<String> capitalOrExpenseSet, String itemIdentifier, ObjectCode objectCode) {
boolean valid = true;
// If the set contains more than one distinct string, fail.
if (capitalOrExpenseSet.size() > 1) {
GlobalVariables.getErrorMap().putError(KFSConstants.FINANCIAL_OBJECT_LEVEL_CODE_PROPERTY_NAME, CabKeyConstants.ERROR_ITEM_CAPITAL_AND_EXPENSE, itemIdentifier, objectCode.getFinancialObjectCodeName());
valid &= false;
}
return valid;
}
protected boolean validateLevelCapitalAssetIndication(BigDecimal unitPrice, ObjectCode objectCode, String itemIdentifier) {
String capitalAssetPriceThresholdParam = this.getParameterService().getParameterValue(AssetGlobal.class, CabParameterConstants.CapitalAsset.CAPITALIZATION_LIMIT_AMOUNT);
BigDecimal priceThreshold = null;
try {
priceThreshold = new BigDecimal(capitalAssetPriceThresholdParam);
}
catch (NumberFormatException nfe) {
throw new RuntimeException("the parameter for CAPITAL_ASSET_OBJECT_LEVELS came was not able to be converted to a number.", nfe);
}
if (unitPrice.compareTo(priceThreshold) >= 0) {
List<String> possibleCAMSObjectLevels = this.getParameterService().getParameterValues(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.POSSIBLE_CAPITAL_ASSET_OBJECT_LEVELS);
if (possibleCAMSObjectLevels.contains(objectCode.getFinancialObjectLevelCode())) {
String warning = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(CabKeyConstants.WARNING_ABOVE_THRESHOLD_SUGESTS_CAPITAL_ASSET_LEVEL);
warning = StringUtils.replace(warning, "{0}", itemIdentifier);
warning = StringUtils.replace(warning, "{1}", priceThreshold.toString());
GlobalVariables.getMessageList().add(warning);
return false;
}
}
return true;
}
/**
* Capital Asset validation: If the item has a transaction type, check that the transaction type is acceptable for the object
* code sub-types of all the object codes on the associated accounting lines.
*
* @param objectCode
* @param capitalAssetTransactionType
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier
* @return
*/
protected boolean validateObjectCodeVersusTransactionType(ObjectCode objectCode, CapitalAssetBuilderAssetTransactionType capitalAssetTransactionType, String itemIdentifier, boolean quantityBasedItem) {
boolean valid = true;
String[] objectCodeSubTypes = {};
if (quantityBasedItem) {
String capitalAssetQuantitySubtypeRequiredText = capitalAssetTransactionType.getCapitalAssetQuantitySubtypeRequiredText();
if (capitalAssetQuantitySubtypeRequiredText != null) {
objectCodeSubTypes = StringUtils.split(capitalAssetQuantitySubtypeRequiredText, ";");
}
}
else {
String capitalAssetNonquantitySubtypeRequiredText = capitalAssetTransactionType.getCapitalAssetNonquantitySubtypeRequiredText();
if (capitalAssetNonquantitySubtypeRequiredText != null) {
objectCodeSubTypes = StringUtils.split(capitalAssetNonquantitySubtypeRequiredText, ";");
}
}
boolean found = false;
for (String subType : objectCodeSubTypes) {
if (StringUtils.equals(subType, objectCode.getFinancialObjectSubTypeCode())) {
found = true;
break;
}
}
if (!found) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_TRAN_TYPE_OBJECT_CODE_SUBTYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), objectCode.getFinancialObjectCodeName(), objectCode.getFinancialObjectSubType().getFinancialObjectSubTypeName());
valid &= false;
}
return valid;
}
/**
* Capital Asset validation: If the item has a transaction type, check that if the document specifies that recurring payments
* are to be made, that the transaction type is one that is appropriate for this situation, and that if the document does not
* specify that recurring payments are to be made, that the transaction type is one that is appropriate for that situation.
*
* @param capitalAssetTransactionType
* @param recurringPaymentType
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier
* @return
*/
protected boolean validateCapitalAssetTransactionTypeVersusRecurrence(CapitalAssetBuilderAssetTransactionType capitalAssetTransactionType, String recurringPaymentTypeCode, String itemIdentifier) {
boolean valid = true;
// If there is a tran type ...
if ((capitalAssetTransactionType != null) && (capitalAssetTransactionType.getCapitalAssetTransactionTypeCode() != null)) {
String recurringTransactionTypeCodes = this.getParameterService().getParameterValue(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.RECURRING_CAMS_TRAN_TYPES);
if (StringUtils.isNotEmpty(recurringPaymentTypeCode)) { // If there is a recurring payment type ...
if (!StringUtils.contains(recurringTransactionTypeCodes, capitalAssetTransactionType.getCapitalAssetTransactionTypeCode())) {
// There should be a recurring tran type code.
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_WRONG_TRAN_TYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), CabConstants.ValidationStrings.RECURRING);
valid &= false;
}
}
else { // If the payment type is not recurring ...
// There should not be a recurring transaction type code.
if (StringUtils.contains(recurringTransactionTypeCodes, capitalAssetTransactionType.getCapitalAssetTransactionTypeCode())) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_WRONG_TRAN_TYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), CabConstants.ValidationStrings.NON_RECURRING);
valid &= false;
}
}
}
else { // If there is no transaction type ...
if (StringUtils.isNotEmpty(recurringPaymentTypeCode)) { // If there is a recurring payment type ...
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_NO_TRAN_TYPE, itemIdentifier, CabConstants.ValidationStrings.RECURRING);
valid &= false;
}
else { // If the payment type is not recurring ...
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_NO_TRAN_TYPE, itemIdentifier, CabConstants.ValidationStrings.NON_RECURRING);
valid &= false;
}
}
return valid;
}
/**
* Utility wrapping isCapitalAssetObjectCode for the use of processItemCapitalAssetValidation.
*
* @param oc An ObjectCode
* @return A String indicating that the given object code is either Capital or Expense
*/
protected String objectCodeCapitalOrExpense(ObjectCode oc) {
String capital = CabConstants.ValidationStrings.CAPITAL;
String expense = CabConstants.ValidationStrings.EXPENSE;
return (isCapitalAssetObjectCode(oc) ? capital : expense);
}
/**
* Predicate to determine whether the given object code is of a specified object sub type required for purap cams.
*
* @param oc An ObjectCode
* @return True if the ObjectSubType is the one designated for capital assets.
*/
protected boolean isCapitalAssetObjectCode(ObjectCode oc) {
String capitalAssetObjectSubType = this.getParameterService().getParameterValue(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, PurapParameterConstants.CapitalAsset.PURCHASING_OBJECT_SUB_TYPES);
return (StringUtils.containsIgnoreCase(capitalAssetObjectSubType, oc.getFinancialObjectSubTypeCode()) ? true : false);
}
protected boolean validateCapitalAssetLocationAddressFieldsOneOrMultipleSystemType(List<CapitalAssetSystem> capitalAssetSystems) {
boolean valid = true;
int systemCount = 0;
for (CapitalAssetSystem system : capitalAssetSystems) {
List<CapitalAssetLocation> capitalAssetLocations = system.getCapitalAssetLocations();
StringBuffer errorKey = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[" + new Integer(systemCount++) + "].");
errorKey.append("capitalAssetLocations");
int locationCount = 0;
for (CapitalAssetLocation location : capitalAssetLocations) {
errorKey.append("[" + locationCount++ + "].");
valid &= validateCapitalAssetLocationAddressFields(location, errorKey);
}
}
return valid;
}
protected boolean validateCapitalAssetLocationAddressFieldsForIndividualSystemType(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
CapitalAssetSystem system = item.getPurchasingCapitalAssetSystem();
List<CapitalAssetLocation> capitalAssetLocations = system.getCapitalAssetLocations();
StringBuffer errorKey = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
errorKey.append("purchasingCapitalAssetSystem.capitalAssetLocations");
int i = 0;
for (CapitalAssetLocation location : capitalAssetLocations) {
errorKey.append("[" + i++ + "].");
valid &= validateCapitalAssetLocationAddressFields(location, errorKey);
}
}
return valid;
}
protected boolean validateCapitalAssetLocationAddressFields(CapitalAssetLocation location, StringBuffer errorKey) {
boolean valid = true;
if (StringUtils.isBlank(location.getCapitalAssetLine1Address())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_ADDRESS_LINE1);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetCityName())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_CITY);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetCountryCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_COUNTRY);
valid &= false;
}
else if (location.getCapitalAssetCountryCode().equals(KFSConstants.COUNTRY_CODE_UNITED_STATES)) {
if (StringUtils.isBlank(location.getCapitalAssetStateCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_STATE);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetPostalCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_POSTAL_CODE);
valid &= false;
}
}
if (!location.isOffCampusIndicator()) {
if (StringUtils.isBlank(location.getCampusCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_CAMPUS);
valid &= false;
}
if (StringUtils.isBlank(location.getBuildingCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_BUILDING);
valid &= false;
}
if (StringUtils.isBlank(location.getBuildingRoomNumber())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_ROOM);
valid &= false;
}
}
return valid;
}
protected boolean validateAccountsPayableItem(AccountsPayableItem apItem) {
boolean valid = true;
valid &= validatePurapItemCapitalAsset(apItem, (AssetTransactionType) apItem.getCapitalAssetTransactionType());
return valid;
}
// end of methods for purap
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#validateFinancialProcessingData(org.kuali.kfs.sys.document.AccountingDocument,
* org.kuali.kfs.fp.businessobject.CapitalAssetInformation)
* @param accountingDocument and capitalAssetInformation
* @return True if the FinancialProcessingData is valid.
*/
public boolean validateFinancialProcessingData(AccountingDocument accountingDocument, CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
// Check if we need to collect cams data
String dataEntryExpected = this.getCapitalAssetObjectSubTypeLinesFlag(accountingDocument);
if (StringUtils.isBlank(dataEntryExpected)) {
// Data is not expected
if (!isCapitalAssetInformationBlank(capitalAssetInformation)) {
// If no parameter was found or determined that data shouldn't be collected, give error if data was entered
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_DO_NOT_ENTER_ANY_DATA);
return false;
}
else {
// No data to be collected and no data entered. Hence no error
return true;
}
}
else {
// Data is expected
if (isCapitalAssetInformationBlank(capitalAssetInformation)) {
// No data is entered
if (isCapitalAssetDataRequired(accountingDocument, dataEntryExpected)) {
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_REQUIRE_DATA_ENTRY);
return false;
}
else
return true;
}
else if (!isNewAssetBlank(capitalAssetInformation) && !canCreateNewAsset(accountingDocument, dataEntryExpected)) {
// No allow to create new capital asset
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_QUANTITY, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_UPDATE_ALLOW_ONLY);
return false;
}
else if (!isNewAssetBlank(capitalAssetInformation) && !isUpdateAssetBlank(capitalAssetInformation)) {
// Data exists on both crate new asset and update asset, give error
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_NEW_OR_UPDATE_ONLY);
return false;
}
}
if (!isUpdateAssetBlank(capitalAssetInformation)) {
// Validate update Asset information
valid = validateUpdateCapitalAssetField(capitalAssetInformation, accountingDocument);
}
else {
// Validate New Asset information
valid = checkNewCapitalAssetFieldsExist(capitalAssetInformation);
if (valid) {
valid = validateNewCapitalAssetFields(capitalAssetInformation);
}
}
return valid;
}
/**
* This method...
*
* @param accountingDocument
* @return getCapitalAssetObjectSubTypeLinesFlag = "" ==> no assetObjectSubType code F ==> assetObjectSubType code on source
* lines T ==> assetObjectSubType code on target lines FT ==> assetObjectSubType code on both source and target lines
*/
protected String getCapitalAssetObjectSubTypeLinesFlag(AccountingDocument accountingDocument) {
List<String> financialProcessingCapitalObjectSubTypes = this.getParameterService().getParameterValues(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.FINANCIAL_PROCESSING_CAPITAL_OBJECT_SUB_TYPES);
String getCapitalAssetObjectSubTypeLinesFlag = "";
// Check if SourceAccountingLine has objectSub type code
List<SourceAccountingLine> sAccountingLines = accountingDocument.getSourceAccountingLines();
for (SourceAccountingLine sourceAccountingLine : sAccountingLines) {
ObjectCode objectCode = sourceAccountingLine.getObjectCode();
if (ObjectUtils.isNull(objectCode)) {
break;
}
String objectSubTypeCode = objectCode.getFinancialObjectSubTypeCode();
if (financialProcessingCapitalObjectSubTypes.contains(objectSubTypeCode)) {
getCapitalAssetObjectSubTypeLinesFlag = KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE;
break;
}
}
// Check if TargetAccountingLine has objectSub type code
List<TargetAccountingLine> tAccountingLines = accountingDocument.getTargetAccountingLines();
for (TargetAccountingLine targetAccountingLine : tAccountingLines) {
ObjectCode objectCode = targetAccountingLine.getObjectCode();
if (ObjectUtils.isNull(objectCode)) {
break;
}
String objectSubTypeCode = objectCode.getFinancialObjectSubTypeCode();
if (financialProcessingCapitalObjectSubTypes.contains(objectSubTypeCode)) {
getCapitalAssetObjectSubTypeLinesFlag = getCapitalAssetObjectSubTypeLinesFlag.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE) ? KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE + KFSConstants.TARGET_ACCT_LINE_TYPE_CODE : KFSConstants.TARGET_ACCT_LINE_TYPE_CODE;
break;
}
}
return getCapitalAssetObjectSubTypeLinesFlag;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#hasCapitalAssetObjectSubType(org.kuali.kfs.sys.document.AccountingDocument)
*/
public boolean hasCapitalAssetObjectSubType(AccountingDocument accountingDocument) {
boolean hasCapitalAssetObjectSubType = false;
if (!getCapitalAssetObjectSubTypeLinesFlag(accountingDocument).equals("N"))
hasCapitalAssetObjectSubType = true;
return hasCapitalAssetObjectSubType;
}
/**
* if the capital asset data is required for this transaction
*
* @param accountingDocument and dataEntryExpected
* @return boolean false then the capital asset information is not required
*/
private boolean isCapitalAssetDataRequired(AccountingDocument accountingDocument, String dataEntryExpected) {
boolean isCapitalAssetDataRequired = true;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
// if (isDocumentTypeRestricted(accountingDocument) ||
// accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING)) {
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING)) {
if (dataEntryExpected.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE + KFSConstants.TARGET_ACCT_LINE_TYPE_CODE))
isCapitalAssetDataRequired = false;
}
return isCapitalAssetDataRequired;
}
/**
* if this transaction can create new asset
*
* @param accountingDocument and dataEntryExpected
* @return
*/
private boolean canCreateNewAsset(AccountingDocument accountingDocument, String dataEntryExpected) {
boolean canCreateNewAsset = true;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.CASH_RECEIPT)) {
canCreateNewAsset = false;
}
else {
if (isDocumentTypeRestricted(accountingDocument) && dataEntryExpected.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE))
canCreateNewAsset = false;
}
return canCreateNewAsset;
}
/**
* if this document is restricted
*
* @param accountingDocument
* @return boolean true then this document is restricted
*/
private boolean isDocumentTypeRestricted(AccountingDocument accountingDocument) {
boolean isDocumentTypeRestricted = false;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.GENERAL_ERROR_CORRECTION) || accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.YEAR_END_GENERAL_ERROR_CORRECTION))
isDocumentTypeRestricted = true;
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.DISTRIBUTION_OF_INCOME_AND_EXPENSE) || accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.YEAR_END_DISTRIBUTION_OF_INCOME_AND_EXPENSE))
isDocumentTypeRestricted = true;
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.SERVICE_BILLING))
isDocumentTypeRestricted = true;
return isDocumentTypeRestricted;
}
/**
* To see if capitalAssetInformation is blank
*
* @param capitalAssetInformation
* @return boolean false if the asset is not blank
*/
private boolean isCapitalAssetInformationBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (!isNewAssetBlank(capitalAssetInformation) || !isUpdateAssetBlank(capitalAssetInformation)) {
isBlank = false;
}
return isBlank;
}
/**
* To check if data exists on create new asset
*
* @param capitalAssetInformation
* @return boolean false if the new asset is not blank
*/
private boolean isNewAssetBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetTypeCode()) || ObjectUtils.isNotNull(capitalAssetInformation.getVendorName()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetQuantity()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetManufacturerName()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetManufacturerModelNumber()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetDescription())) {
isBlank = false;
}
return isBlank;
}
/**
* To check if data exists on update asset
*
* @param capitalAssetInformation
* @return boolean false if the update asset is not blank
*/
private boolean isUpdateAssetBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetNumber())) {
isBlank = false;
}
return isBlank;
}
/**
* To validate if the asset is active
*
* @param capitalAssetManagementAsset the asset to be validated
* @return boolean false if the asset is not active
*/
private boolean validateUpdateCapitalAssetField(CapitalAssetInformation capitalAssetInformation, AccountingDocument accountingDocument) {
boolean valid = true;
Map<String, String> params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, capitalAssetInformation.getCapitalAssetNumber().toString());
Asset asset = (Asset) this.getBusinessObjectService().findByPrimaryKey(Asset.class, params);
List<Long> assetNumbers = new ArrayList<Long>();
assetNumbers.add(capitalAssetInformation.getCapitalAssetNumber());
if (ObjectUtils.isNull(asset)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_NUMBER);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, KFSKeyConstants.ERROR_EXISTENCE, label);
}
else if (!(this.getAssetService().isCapitalAsset(asset) && !this.getAssetService().isAssetRetired(asset))) {
// check asset status must be capital asset active.
valid = false;
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_ACTIVE_CAPITAL_ASSET_REQUIRED);
}
else {
String documentNumber = accountingDocument.getDocumentNumber();
String documentType = getDocumentTypeName(accountingDocument);
if (getCapitalAssetManagementModuleService().isFpDocumentEligibleForAssetLock(accountingDocument, documentType) && getCapitalAssetManagementModuleService().isAssetLocked(assetNumbers, documentType, documentNumber)) {
valid = false;
}
}
return valid;
}
/**
* Check if all required fields exist on new asset
*
* @param capitalAssetInformation the fields of add asset to be checked
* @return boolean false if a required field is missing
*/
private boolean checkNewCapitalAssetFieldsExist(CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetTypeCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (capitalAssetInformation.getCapitalAssetQuantity() == null || capitalAssetInformation.getCapitalAssetQuantity() <= 0) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_QUANTITY);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_QUANTITY, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getVendorName())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.VENDOR_NAME);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.VENDOR_NAME, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetManufacturerName())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_MANUFACTURE_NAME);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_MANUFACTURE_NAME, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetDescription())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, CamsPropertyConstants.Asset.CAPITAL_ASSET_DESCRIPTION);
GlobalVariables.getErrorMap().putError(CamsPropertyConstants.Asset.CAPITAL_ASSET_DESCRIPTION, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
int index = 0;
List<CapitalAssetInformationDetail> capitalAssetInformationDetails = capitalAssetInformation.getCapitalAssetInformationDetails();
for (CapitalAssetInformationDetail dtl : capitalAssetInformationDetails) {
String errorPathPrefix = KFSPropertyConstants.DOCUMENT + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION_DETAILS;
if (StringUtils.isBlank(dtl.getCampusCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(Campus.class, KFSPropertyConstants.CAMPUS_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAMPUS_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(dtl.getBuildingCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(Building.class, KFSPropertyConstants.BUILDING_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(dtl.getBuildingRoomNumber())) {
String label = this.getDataDictionaryService().getAttributeLabel(Room.class, KFSPropertyConstants.BUILDING_ROOM_NUMBER);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_ROOM_NUMBER, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
index++;
}
return valid;
}
/**
* To validate new asset information
*
* @param capitalAssetInformation the information of add asset to be validated
* @return boolean false if data is incorrect
*/
private boolean validateNewCapitalAssetFields(CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
Map<String, String> params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, capitalAssetInformation.getCapitalAssetTypeCode().toString());
AssetType assetType = (AssetType) this.getBusinessObjectService().findByPrimaryKey(AssetType.class, params);
if (ObjectUtils.isNull(assetType)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, KFSKeyConstants.ERROR_EXISTENCE, label);
}
int index = 0;
List<CapitalAssetInformationDetail> capitalAssetInformationDetails = capitalAssetInformation.getCapitalAssetInformationDetails();
for (CapitalAssetInformationDetail dtl : capitalAssetInformationDetails) {
// We have to explicitly call this DD service to uppercase each field. This may not be the best place and maybe form
// populate
// is a better place but we CAMS team don't own FP document. This is the best we can do for now.
SpringContext.getBean(BusinessObjectDictionaryService.class).performForceUppercase(dtl);
String errorPathPrefix = KFSPropertyConstants.DOCUMENT + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION_DETAILS;
if (StringUtils.isNotBlank(dtl.getCapitalAssetTagNumber()) && !dtl.getCapitalAssetTagNumber().equalsIgnoreCase(CamsConstants.Asset.NON_TAGGABLE_ASSET)) {
if (isTagNumberDuplicate(capitalAssetInformationDetails, dtl)) {
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAPITAL_ASSET_TAG_NUMBER, CamsKeyConstants.AssetGlobal.ERROR_CAMPUS_TAG_NUMBER_DUPLICATE, dtl.getCapitalAssetTagNumber());
valid = false;
}
}
Map<String, Object> criteria = new HashMap<String, Object>();
criteria.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
Campus campus = (Campus) SpringContext.getBean(KualiModuleService.class).getResponsibleModuleService(Campus.class).getExternalizableBusinessObject(Campus.class, criteria);
if (ObjectUtils.isNull(campus)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(Campus.class, KFSPropertyConstants.CAMPUS_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAMPUS_CODE, KFSKeyConstants.ERROR_EXISTENCE, label);
}
params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
params.put(KFSPropertyConstants.BUILDING_CODE, dtl.getBuildingCode());
Building building = (Building) this.getBusinessObjectService().findByPrimaryKey(Building.class, params);
if (ObjectUtils.isNull(building)) {
valid = false;
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_CODE, CamsKeyConstants.AssetLocationGlobal.ERROR_INVALID_BUILDING_CODE, dtl.getBuildingCode(), dtl.getCampusCode());
}
params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
params.put(KFSPropertyConstants.BUILDING_CODE, dtl.getBuildingCode());
params.put(KFSPropertyConstants.BUILDING_ROOM_NUMBER, dtl.getBuildingRoomNumber());
Room room = (Room) this.getBusinessObjectService().findByPrimaryKey(Room.class, params);
if (ObjectUtils.isNull(room)) {
valid = false;
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_ROOM_NUMBER, CamsKeyConstants.AssetLocationGlobal.ERROR_INVALID_ROOM_NUMBER, dtl.getBuildingRoomNumber(), dtl.getBuildingCode(), dtl.getCampusCode());
}
index++;
}
return valid;
}
/**
* To check if the tag number is duplicate or in use
*
* @param capitalAssetInformation, capitalAssetInformationDetail
* @return boolean false if data is duplicate or in use
*/
private boolean isTagNumberDuplicate(List<CapitalAssetInformationDetail> capitalAssetInformationDetails, CapitalAssetInformationDetail dtl) {
boolean duplicateTag = false;
int tagCounter = 0;
if (!this.getAssetService().findActiveAssetsMatchingTagNumber(dtl.getCapitalAssetTagNumber()).isEmpty()) {
// Tag number is already in use
duplicateTag = true;
}
else {
for (CapitalAssetInformationDetail capitalAssetInfoDetl : capitalAssetInformationDetails) {
if (capitalAssetInfoDetl.getCapitalAssetTagNumber().equalsIgnoreCase(dtl.getCapitalAssetTagNumber().toString())) {
tagCounter++;
}
}
if (tagCounter > 1) {
// Tag number already exists in the collection
duplicateTag = true;
}
}
return duplicateTag;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#notifyRouteStatusChange(java.lang.String,
* java.lang.String)
*/
public void notifyRouteStatusChange(DocumentHeader documentHeader) {
KualiWorkflowDocument workflowDocument = documentHeader.getWorkflowDocument();
String documentNumber = documentHeader.getDocumentNumber();
String documentType = workflowDocument.getDocumentType();
if (workflowDocument.stateIsCanceled() || workflowDocument.stateIsDisapproved()) {
// release CAB line items
activateCabPOLines(documentNumber);
activateCabGlLines(documentNumber);
}
if (workflowDocument.stateIsProcessed()) {
// update CAB GL lines if fully processed
updatePOLinesStatusAsProcessed(documentNumber);
updateGlLinesStatusAsProcessed(documentNumber);
// report asset numbers to PO
Integer poId = getPurchaseOrderIdentifier(documentNumber);
if (poId != null) {
List<Long> assetNumbers = null;
if (DocumentTypeName.ASSET_ADD_GLOBAL.equalsIgnoreCase(documentType)) {
assetNumbers = getAssetNumbersFromAssetGlobal(documentNumber);
}
else if (DocumentTypeName.ASSET_PAYMENT.equalsIgnoreCase(documentType)) {
assetNumbers = getAssetNumbersFromAssetPayment(documentNumber);
}
if (!assetNumbers.isEmpty()) {
String noteText = buildNoteTextForPurApDoc(documentType, assetNumbers);
SpringContext.getBean(PurchasingAccountsPayableModuleService.class).addAssignedAssetNumbers(poId, workflowDocument.getInitiatorPrincipalId(), noteText);
}
}
}
}
/**
* update cab non-PO lines status code for item/account/glEntry to 'P' as fully processed when possible
*
* @param documentNumber
*/
protected void updateGlLinesStatusAsProcessed(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<GeneralLedgerEntryAsset> matchingGlAssets = this.getBusinessObjectService().findMatching(GeneralLedgerEntryAsset.class, fieldValues);
if (matchingGlAssets != null && !matchingGlAssets.isEmpty()) {
for (GeneralLedgerEntryAsset generalLedgerEntryAsset : matchingGlAssets) {
GeneralLedgerEntry generalLedgerEntry = generalLedgerEntryAsset.getGeneralLedgerEntry();
// update gl status as processed
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
this.getBusinessObjectService().save(generalLedgerEntry);
// release asset lock
if (isFpDocumentFullyProcessed(generalLedgerEntry)) {
getCapitalAssetManagementModuleService().deleteAssetLocks(generalLedgerEntry.getDocumentNumber(), null);
}
}
}
}
/**
* Check all generalLedgerEntries from the same FP document are fully processed.
*
* @param generalLedgerEntry
* @return
*/
protected boolean isFpDocumentFullyProcessed(GeneralLedgerEntry generalLedgerEntry) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.GeneralLedgerEntry.DOCUMENT_NUMBER, generalLedgerEntry.getDocumentNumber());
Collection<GeneralLedgerEntry> matchingGlEntries = this.getBusinessObjectService().findMatching(GeneralLedgerEntry.class, fieldValues);
for (GeneralLedgerEntry glEntry : matchingGlEntries) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(glEntry.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* update CAB PO lines status code for item/account/glEntry to 'P' as fully processed when possible
*
* @param documentNumber
*/
protected void updatePOLinesStatusAsProcessed(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingAssets = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
if (matchingAssets != null && !matchingAssets.isEmpty()) {
// Map<Long, GeneralLedgerEntry> updateGlLines = new HashMap<Long, GeneralLedgerEntry>();
// update item and account status code to 'P' as fully processed
for (PurchasingAccountsPayableItemAsset itemAsset : matchingAssets) {
itemAsset.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
for (PurchasingAccountsPayableLineAssetAccount assetAccount : itemAsset.getPurchasingAccountsPayableLineAssetAccounts()) {
assetAccount.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
GeneralLedgerEntry generalLedgerEntry = assetAccount.getGeneralLedgerEntry();
// updateGlLines.put(generalLedgerEntry.getGeneralLedgerAccountIdentifier(), generalLedgerEntry);
if (isGlEntryFullyProcessed(generalLedgerEntry)) {
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
this.getBusinessObjectService().save(generalLedgerEntry);
}
}
// update cab document status code to 'P' as all its items fully processed
PurchasingAccountsPayableDocument purapDocument = itemAsset.getPurchasingAccountsPayableDocument();
if (isDocumentFullyProcessed(purapDocument)) {
purapDocument.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
}
this.getBusinessObjectService().save(purapDocument);
String lockingInformation = null;
PurchaseOrderDocument poDocument = getPurApInfoService().getCurrentDocumentForPurchaseOrderIdentifier(purapDocument.getPurchaseOrderIdentifier());
// Only individual system will lock on item line number. other system will using preq/cm doc nbr as the locking
// key
if (PurapConstants.CapitalAssetTabStrings.INDIVIDUAL_ASSETS.equalsIgnoreCase(poDocument.getCapitalAssetSystemTypeCode())) {
lockingInformation = itemAsset.getAccountsPayableLineItemIdentifier().toString();
}
// release the asset lock no matter if it's Asset global or Asset Payment since the CAB user can create Asset global
// doc even if Purap Asset numbers existing.
if (isAccountsPayableItemLineFullyProcessed(purapDocument, lockingInformation)) {
getCapitalAssetManagementModuleService().deleteAssetLocks(purapDocument.getDocumentNumber(), lockingInformation);
}
}
}
}
/**
* If lockingInformation is not empty, check all item lines from the same PurAp item are fully processed. If lockingInformation
* is empty, we check all items from the same PREQ/CM document processed as fully processed.
*
* @param itemAsset
* @return
*/
protected boolean isAccountsPayableItemLineFullyProcessed(PurchasingAccountsPayableDocument purapDocument, String lockingInformation) {
for (PurchasingAccountsPayableItemAsset item : purapDocument.getPurchasingAccountsPayableItemAssets()) {
if ((StringUtils.isBlank(lockingInformation) && !CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(item.getActivityStatusCode())) || (StringUtils.isNotBlank(lockingInformation) && item.getAccountsPayableLineItemIdentifier().equals(lockingInformation) && !CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(item.getActivityStatusCode()))) {
return false;
}
}
return true;
}
/**
* Check if Gl Entry related accounts are fully processed
*
* @param glEntry
* @return
*/
protected boolean isGlEntryFullyProcessed(GeneralLedgerEntry glEntry) {
for (PurchasingAccountsPayableLineAssetAccount account : glEntry.getPurApLineAssetAccounts()) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equalsIgnoreCase(account.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* Check if PurApDocument related items are fully processed.
*
* @param purapDocument
* @return
*/
protected boolean isDocumentFullyProcessed(PurchasingAccountsPayableDocument purapDocument) {
for (PurchasingAccountsPayableItemAsset item : purapDocument.getPurchasingAccountsPayableItemAssets()) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equalsIgnoreCase(item.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* Build the appropriate note text being set to the purchase order document.
*
* @param documentType
* @param assetNumbers
* @return
*/
private String buildNoteTextForPurApDoc(String documentType, List<Long> assetNumbers) {
StringBuffer noteText = new StringBuffer();
if (DocumentTypeName.ASSET_ADD_GLOBAL.equalsIgnoreCase(documentType)) {
noteText.append("Asset Numbers have been created for this document: ");
}
else {
noteText.append("Existing Asset Numbers have been applied for this document: ");
}
for (int i = 0; i < assetNumbers.size(); i++) {
noteText.append(assetNumbers.get(i).toString());
if (i < assetNumbers.size() - 1) {
noteText.append(", ");
}
}
return noteText.toString();
}
/**
* Acquire asset numbers from CAMS asset payment document.
*
* @param documentNumber
* @param assetNumbers
*/
private List<Long> getAssetNumbersFromAssetGlobal(String documentNumber) {
List<Long> assetNumbers = new ArrayList<Long>();
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CamsPropertyConstants.AssetGlobalDetail.DOCUMENT_NUMBER, documentNumber);
Collection<AssetGlobalDetail> assetGlobalDetails = this.getBusinessObjectService().findMatching(AssetGlobalDetail.class, fieldValues);
for (AssetGlobalDetail detail : assetGlobalDetails) {
assetNumbers.add(detail.getCapitalAssetNumber());
}
return assetNumbers;
}
/**
* Acquire asset numbers from CAMS asset global document.
*
* @param documentNumber
* @param assetNumbers
*/
private List<Long> getAssetNumbersFromAssetPayment(String documentNumber) {
List<Long> assetNumbers = new ArrayList<Long>();
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CamsPropertyConstants.DOCUMENT_NUMBER, documentNumber);
Collection<AssetPaymentAssetDetail> paymentAssetDetails = this.getBusinessObjectService().findMatching(AssetPaymentAssetDetail.class, fieldValues);
for (AssetPaymentAssetDetail detail : paymentAssetDetails) {
if (ObjectUtils.isNotNull(detail.getAsset())) {
assetNumbers.add(detail.getCapitalAssetNumber());
}
}
return assetNumbers;
}
/**
* Query PurchasingAccountsPayableItemAsset and return the purchaseOrderIdentifier if the given documentNumber is initiated from
* the PurAp line.
*
* @param documentNumber
* @return
*/
private Integer getPurchaseOrderIdentifier(String camsDocumentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, camsDocumentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingItems = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
for (PurchasingAccountsPayableItemAsset item : matchingItems) {
if (ObjectUtils.isNull(item.getPurchasingAccountsPayableDocument())) {
item.refreshReferenceObject(CabPropertyConstants.PurchasingAccountsPayableItemAsset.PURCHASING_ACCOUNTS_PAYABLE_DOCUMENT);
}
return item.getPurchasingAccountsPayableDocument().getPurchaseOrderIdentifier();
}
return null;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#getCurrentPurchaseOrderDocumentNumber(java.lang.String)
*/
public String getCurrentPurchaseOrderDocumentNumber(String camsDocumentNumber) {
Integer poId = getPurchaseOrderIdentifier(camsDocumentNumber);
if (poId != null) {
PurchaseOrderDocument poDocument = getPurApInfoService().getCurrentDocumentForPurchaseOrderIdentifier(poId);
if (ObjectUtils.isNotNull(poDocument)) {
return poDocument.getDocumentNumber();
}
}
return null;
}
/**
* Activates CAB GL Lines
*
* @param documentNumber String
*/
protected void activateCabGlLines(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<GeneralLedgerEntryAsset> matchingGlAssets = this.getBusinessObjectService().findMatching(GeneralLedgerEntryAsset.class, fieldValues);
if (matchingGlAssets != null && !matchingGlAssets.isEmpty()) {
for (GeneralLedgerEntryAsset generalLedgerEntryAsset : matchingGlAssets) {
GeneralLedgerEntry generalLedgerEntry = generalLedgerEntryAsset.getGeneralLedgerEntry();
generalLedgerEntry.setTransactionLedgerSubmitAmount(KualiDecimal.ZERO);
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.NEW);
this.getBusinessObjectService().save(generalLedgerEntry);
this.getBusinessObjectService().delete(generalLedgerEntryAsset);
}
}
}
/**
* Activates PO Lines
*
* @param documentNumber String
*/
protected void activateCabPOLines(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingPoAssets = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
if (matchingPoAssets != null && !matchingPoAssets.isEmpty()) {
for (PurchasingAccountsPayableItemAsset itemAsset : matchingPoAssets) {
PurchasingAccountsPayableDocument purapDocument = itemAsset.getPurchasingAccountsPayableDocument();
purapDocument.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(purapDocument);
itemAsset.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(itemAsset);
List<PurchasingAccountsPayableLineAssetAccount> lineAssetAccounts = itemAsset.getPurchasingAccountsPayableLineAssetAccounts();
for (PurchasingAccountsPayableLineAssetAccount assetAccount : lineAssetAccounts) {
assetAccount.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(assetAccount);
GeneralLedgerEntry generalLedgerEntry = assetAccount.getGeneralLedgerEntry();
KualiDecimal submitAmount = generalLedgerEntry.getTransactionLedgerSubmitAmount();
if (submitAmount == null) {
submitAmount = KualiDecimal.ZERO;
}
submitAmount = submitAmount.subtract(assetAccount.getItemAccountTotalAmount());
generalLedgerEntry.setTransactionLedgerSubmitAmount(submitAmount);
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(generalLedgerEntry);
}
}
}
}
/**
* gets the document type based on the instance of a class
*
* @param accountingDocument
* @return
*/
private String getDocumentTypeName(AccountingDocument accountingDocument) {
String documentTypeName = null;
if (accountingDocument instanceof YearEndGeneralErrorCorrectionDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.YEAR_END_GENERAL_ERROR_CORRECTION;
else if (accountingDocument instanceof YearEndDistributionOfIncomeAndExpenseDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.YEAR_END_DISTRIBUTION_OF_INCOME_AND_EXPENSE;
else if (accountingDocument instanceof ServiceBillingDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.SERVICE_BILLING;
else if (accountingDocument instanceof GeneralErrorCorrectionDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.GENERAL_ERROR_CORRECTION;
else if (accountingDocument instanceof CashReceiptDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.CASH_RECEIPT;
else if (accountingDocument instanceof DistributionOfIncomeAndExpenseDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.DISTRIBUTION_OF_INCOME_AND_EXPENSE;
else if (accountingDocument instanceof InternalBillingDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING;
else if (accountingDocument instanceof ProcurementCardDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.PROCUREMENT_CARD;
else
throw new RuntimeException("Invalid FP document type.");
return documentTypeName;
}
public ParameterService getParameterService() {
return SpringContext.getBean(ParameterService.class);
}
public BusinessObjectService getBusinessObjectService() {
return SpringContext.getBean(BusinessObjectService.class);
}
public DataDictionaryService getDataDictionaryService() {
return SpringContext.getBean(DataDictionaryService.class);
}
public AssetService getAssetService() {
return SpringContext.getBean(AssetService.class);
}
public KualiModuleService getKualiModuleService() {
return SpringContext.getBean(KualiModuleService.class);
}
public CapitalAssetManagementModuleService getCapitalAssetManagementModuleService() {
return SpringContext.getBean(CapitalAssetManagementModuleService.class);
}
private PurApInfoService getPurApInfoService() {
return SpringContext.getBean(PurApInfoService.class);
}
}
| work/src/org/kuali/kfs/module/cab/service/impl/CapitalAssetBuilderModuleServiceImpl.java | /*
* Copyright 2008 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.cab.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.kfs.coa.businessobject.ObjectCode;
import org.kuali.kfs.fp.businessobject.CapitalAssetInformation;
import org.kuali.kfs.fp.businessobject.CapitalAssetInformationDetail;
import org.kuali.kfs.fp.document.CashReceiptDocument;
import org.kuali.kfs.fp.document.DistributionOfIncomeAndExpenseDocument;
import org.kuali.kfs.fp.document.GeneralErrorCorrectionDocument;
import org.kuali.kfs.fp.document.InternalBillingDocument;
import org.kuali.kfs.fp.document.ProcurementCardDocument;
import org.kuali.kfs.fp.document.ServiceBillingDocument;
import org.kuali.kfs.fp.document.YearEndDistributionOfIncomeAndExpenseDocument;
import org.kuali.kfs.fp.document.YearEndGeneralErrorCorrectionDocument;
import org.kuali.kfs.integration.cab.CapitalAssetBuilderAssetTransactionType;
import org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService;
import org.kuali.kfs.integration.cam.CapitalAssetManagementModuleService;
import org.kuali.kfs.integration.purap.CapitalAssetLocation;
import org.kuali.kfs.integration.purap.CapitalAssetSystem;
import org.kuali.kfs.integration.purap.ExternalPurApItem;
import org.kuali.kfs.integration.purap.ItemCapitalAsset;
import org.kuali.kfs.integration.purap.PurchasingAccountsPayableModuleService;
import org.kuali.kfs.module.cab.CabConstants;
import org.kuali.kfs.module.cab.CabKeyConstants;
import org.kuali.kfs.module.cab.CabParameterConstants;
import org.kuali.kfs.module.cab.CabPropertyConstants;
import org.kuali.kfs.module.cab.businessobject.AssetTransactionType;
import org.kuali.kfs.module.cab.businessobject.GeneralLedgerEntry;
import org.kuali.kfs.module.cab.businessobject.GeneralLedgerEntryAsset;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableDocument;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableItemAsset;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableLineAssetAccount;
import org.kuali.kfs.module.cab.document.service.PurApInfoService;
import org.kuali.kfs.module.cam.CamsConstants;
import org.kuali.kfs.module.cam.CamsKeyConstants;
import org.kuali.kfs.module.cam.CamsPropertyConstants;
import org.kuali.kfs.module.cam.CamsConstants.DocumentTypeName;
import org.kuali.kfs.module.cam.businessobject.Asset;
import org.kuali.kfs.module.cam.businessobject.AssetGlobal;
import org.kuali.kfs.module.cam.businessobject.AssetGlobalDetail;
import org.kuali.kfs.module.cam.businessobject.AssetPaymentAssetDetail;
import org.kuali.kfs.module.cam.businessobject.AssetType;
import org.kuali.kfs.module.cam.document.service.AssetService;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.PurapKeyConstants;
import org.kuali.kfs.module.purap.PurapParameterConstants;
import org.kuali.kfs.module.purap.PurapPropertyConstants;
import org.kuali.kfs.module.purap.businessobject.AccountsPayableItem;
import org.kuali.kfs.module.purap.businessobject.AvailabilityMatrix;
import org.kuali.kfs.module.purap.businessobject.PurApAccountingLine;
import org.kuali.kfs.module.purap.businessobject.PurApItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingCapitalAssetItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingItemBase;
import org.kuali.kfs.module.purap.businessobject.PurchasingItemCapitalAssetBase;
import org.kuali.kfs.module.purap.document.AccountsPayableDocument;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.module.purap.document.PurchasingDocument;
import org.kuali.kfs.module.purap.document.RequisitionDocument;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.businessobject.AccountingLine;
import org.kuali.kfs.sys.businessobject.Building;
import org.kuali.kfs.sys.businessobject.Room;
import org.kuali.kfs.sys.businessobject.SourceAccountingLine;
import org.kuali.kfs.sys.businessobject.TargetAccountingLine;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.AccountingDocument;
import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
import org.kuali.rice.kns.bo.Campus;
import org.kuali.rice.kns.bo.DocumentHeader;
import org.kuali.rice.kns.bo.Parameter;
import org.kuali.rice.kns.datadictionary.AttributeDefinition;
import org.kuali.rice.kns.datadictionary.BusinessObjectEntry;
import org.kuali.rice.kns.service.BusinessObjectDictionaryService;
import org.kuali.rice.kns.service.BusinessObjectService;
import org.kuali.rice.kns.service.DataDictionaryService;
import org.kuali.rice.kns.service.DictionaryValidationService;
import org.kuali.rice.kns.service.KualiConfigurationService;
import org.kuali.rice.kns.service.KualiModuleService;
import org.kuali.rice.kns.service.ParameterService;
import org.kuali.rice.kns.util.GlobalVariables;
import org.kuali.rice.kns.util.KualiDecimal;
import org.kuali.rice.kns.util.ObjectUtils;
import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument;
public class CapitalAssetBuilderModuleServiceImpl implements CapitalAssetBuilderModuleService {
private static Logger LOG = Logger.getLogger(CapitalAssetBuilderModuleService.class);
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#getAllAssetTransactionTypes()
*/
public List<CapitalAssetBuilderAssetTransactionType> getAllAssetTransactionTypes() {
Class<? extends CapitalAssetBuilderAssetTransactionType> assetTransactionTypeClass = this.getKualiModuleService().getResponsibleModuleService(CapitalAssetBuilderAssetTransactionType.class).getExternalizableBusinessObjectImplementation(CapitalAssetBuilderAssetTransactionType.class);
return (List<CapitalAssetBuilderAssetTransactionType>) this.getBusinessObjectService().findAll(assetTransactionTypeClass);
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#validatePurchasingAccountsPayableData(org.kuali.kfs.sys.document.AccountingDocument)
*/
public boolean validatePurchasingData(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
String documentType = (purchasingDocument instanceof RequisitionDocument) ? "REQUISITION" : "PURCHASE_ORDER";
if (PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateIndividualCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
else if (PurapConstants.CapitalAssetSystemTypes.ONE_SYSTEM.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateOneSystemCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetSystems(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
else if (PurapConstants.CapitalAssetSystemTypes.MULTIPLE.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateMultipleSystemsCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetSystems(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
return false;
}
public boolean validateAccountsPayableData(AccountingDocument accountingDocument) {
AccountsPayableDocument apDocument = (AccountsPayableDocument) accountingDocument;
boolean valid = true;
for (PurApItem purApItem : apDocument.getItems()) {
AccountsPayableItem accountsPayableItem = (AccountsPayableItem) purApItem;
// only run on ap items that were line items (not additional charge items) and were cams items
if ((!accountsPayableItem.getItemType().isAdditionalChargeIndicator()) && StringUtils.isNotEmpty(accountsPayableItem.getCapitalAssetTransactionTypeCode())) {
valid &= validateAccountsPayableItem(accountsPayableItem);
}
}
return valid;
}
/**
* Perform the item level capital asset validation to determine if the given document is not allowed to become an Automatic
* Purchase Order (APO). The APO is not allowed if any accounting strings on the document are using an object level indicated as
* capital via a parameter setting.
*/
public boolean doesAccountingLineFailAutomaticPurchaseOrderRules(AccountingLine accountingLine) {
PurApAccountingLine purapAccountingLine = (PurApAccountingLine) accountingLine;
purapAccountingLine.refreshNonUpdateableReferences();
return getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.CAPITAL_ASSET_OBJECT_LEVELS, purapAccountingLine.getObjectCode().getFinancialObjectLevelCode()).evaluationSucceeds();
}
/**
* Perform the document level capital asset validation to determine if the given document is not allowed to become an Automatic
* Purchase Order (APO). The APO is not allowed if any capital asset items exist on the document.
*/
public boolean doesDocumentFailAutomaticPurchaseOrderRules(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
return ObjectUtils.isNotNull(purchasingDocument.getPurchasingCapitalAssetItems()) && !purchasingDocument.getPurchasingCapitalAssetItems().isEmpty();
}
public boolean validateAutomaticPurchaseOrderRule(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
for (PurApItem item : purchasingDocument.getItems()) {
if (doesItemNeedCapitalAsset(item.getItemTypeCode(), item.getSourceAccountingLines())) {
// if the item needs capital asset, we cannot have an APO, so return false.
return false;
}
}
return true;
}
public boolean doesItemNeedCapitalAsset(String itemTypeCode, List accountingLines) {
if (PurapConstants.ItemTypeCodes.ITEM_TYPE_TRADE_IN_CODE.equals(itemTypeCode)) {
// FIXME: Chris - this should be true but need to look to see where itemline number is referenced first
// return true;
return false;
}// else
for (Iterator iterator = accountingLines.iterator(); iterator.hasNext();) {
PurApAccountingLine accountingLine = (PurApAccountingLine) iterator.next();
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
if (isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
return true;
}
}
return false;
}
public boolean validateUpdateCAMSView(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
boolean valid = true;
for (PurApItem purapItem : purchasingDocument.getItems()) {
if (purapItem.getItemType().isLineItemIndicator()) {
if (!doesItemNeedCapitalAsset(purapItem.getItemTypeCode(), purapItem.getSourceAccountingLines())) {
PurchasingCapitalAssetItem camsItem = ((PurchasingItem) purapItem).getPurchasingCapitalAssetItem();
if (camsItem != null && !camsItem.isEmpty()) {
valid = false;
GlobalVariables.getErrorMap().putError("newPurchasingItemCapitalAssetLine", PurapKeyConstants.ERROR_CAPITAL_ASSET_ITEM_NOT_CAMS_ELIGIBLE, "in line item # " + purapItem.getItemLineNumber());
}
}
}
}
return valid;
}
public boolean validateAddItemCapitalAssetBusinessRules(ItemCapitalAsset asset) {
boolean valid = true;
if (asset.getCapitalAssetNumber() == null) {
valid = false;
}
else {
valid = SpringContext.getBean(DictionaryValidationService.class).isBusinessObjectValid((PurchasingItemCapitalAssetBase) asset);
}
if (!valid) {
String propertyName = "newPurchasingItemCapitalAssetLine." + PurapPropertyConstants.CAPITAL_ASSET_NUMBER;
String errorKey = PurapKeyConstants.ERROR_CAPITAL_ASSET_ASSET_NUMBER_MUST_BE_LONG_NOT_NULL;
GlobalVariables.getErrorMap().putError(propertyName, errorKey);
}
return valid;
}
public boolean warningObjectLevelCapital(AccountingDocument accountingDocument) {
org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument purapDocument = (org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument) accountingDocument;
for (PurApItem item : purapDocument.getItems()) {
if (item.getItemType().isLineItemIndicator() && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
List<PurApAccountingLine> accounts = item.getSourceAccountingLines();
BigDecimal unitPrice = item.getItemUnitPrice();
String itemIdentifier = item.getItemIdentifierString();
for (PurApAccountingLine account : accounts) {
ObjectCode objectCode = account.getObjectCode();
if (!validateLevelCapitalAssetIndication(unitPrice, objectCode, itemIdentifier)) {
// found an error
return false;
}
}
}
}
// no need for error
return true;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for individual system type. This also
* calls validations for quantity on locations equal quantity on line items, validates that the transaction type allows asset
* number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateIndividualCapitalAssetSystemFromPurchasing(String systemState, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
// For Individual Asset system type, the List of CapitalAssetSystems in the input parameter for
// validateAllFieldRequirementsByChart
// should be null. So we'll pass in a null here.
boolean valid = validateAllFieldRequirementsByChart(systemState, null, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL);
valid &= validateQuantityOnLocationsEqualsQuantityOnItem(capitalAssetItems, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL, systemState);
valid &= validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers(capitalAssetItems);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for one system type. This also calls
* validations that the transaction type allows asset number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateOneSystemCapitalAssetSystemFromPurchasing(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
boolean valid = validateAllFieldRequirementsByChart(systemState, capitalAssetSystems, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.ONE_SYSTEM);
String capitalAssetTransactionType = capitalAssetItems.get(0).getCapitalAssetTransactionTypeCode();
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[0].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetSystems.get(0), capitalAssetTransactionType, prefix);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for multiple system type. This also calls
* validations that the transaction type allows asset number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateMultipleSystemsCapitalAssetSystemFromPurchasing(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
boolean valid = validateAllFieldRequirementsByChart(systemState, capitalAssetSystems, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.MULTIPLE);
String capitalAssetTransactionType = capitalAssetItems.get(0).getCapitalAssetTransactionTypeCode();
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[0].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetSystems.get(0), capitalAssetTransactionType, prefix);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates all the field requirements by chart. It obtains a List of parameters where the parameter names are like
* "CHARTS_REQUIRING%" then loop through these parameters. If the system type is individual then invoke the
* validateFieldRequirementByChartForIndividualSystemType for further validation, otherwise invoke the
* validateFieldRequirementByChartForOneOrMultipleSystemType for further validation.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @param systemType
* @return
*/
protected boolean validateAllFieldRequirementsByChart(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType, String systemType) {
boolean valid = true;
List<Parameter> results = new ArrayList<Parameter>();
Map<String, String> criteria = new HashMap<String, String>();
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAMESPACE_CODE, CabConstants.Parameters.NAMESPACE);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_DETAIL_TYPE_CODE, CabConstants.Parameters.DETAIL_TYPE_DOCUMENT);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAME, "CHARTS_REQUIRING%" + documentType);
results.addAll(SpringContext.getBean(ParameterService.class).retrieveParametersGivenLookupCriteria(criteria));
for (Parameter parameter : results) {
if (ObjectUtils.isNotNull(parameter)) {
if (systemType.equals(PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL)) {
valid &= validateFieldRequirementByChartForIndividualSystemType(systemState, capitalAssetItems, chartCode, parameter.getParameterName(), parameter.getParameterValue());
}
else {
valid &= validateFieldRequirementByChartForOneOrMultipleSystemType(systemType, systemState, capitalAssetSystems, capitalAssetItems, chartCode, parameter.getParameterName(), parameter.getParameterValue());
}
}
}
return valid;
}
/**
* Validates all the field requirements by chart. It obtains a List of parameters where the parameter names are like
* "CHARTS_REQUIRING%" then loop through these parameters. If any of the parameter's values is null, then return false
*
* @param accountingDocument
* @return
*/
public boolean validateAllFieldRequirementsByChart(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
String documentType = (purchasingDocument instanceof RequisitionDocument) ? "REQUISITION" : "PURCHASE_ORDER";
boolean valid = true;
List<Parameter> results = new ArrayList<Parameter>();
Map<String, String> criteria = new HashMap<String, String>();
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAMESPACE_CODE, CabConstants.Parameters.NAMESPACE);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_DETAIL_TYPE_CODE, CabConstants.Parameters.DETAIL_TYPE_DOCUMENT);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAME, "CHARTS_REQUIRING%" + documentType);
results.addAll(SpringContext.getBean(ParameterService.class).retrieveParametersGivenLookupCriteria(criteria));
for (Parameter parameter : results) {
if (ObjectUtils.isNotNull(parameter)) {
if (parameter.getParameterValue() != null) {
return false;
}
}
}
return valid;
}
/**
* Validates for PURCHASING_OBJECT_SUB_TYPES parameter. If at least one object code of any accounting line entered is of this
* type, then return false.
*
* @param accountingDocument
* @return
*/
public boolean validatePurchasingObjectSubType(AccountingDocument accountingDocument) {
boolean valid = true;
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
for (PurApItem item : purchasingDocument.getItems()) {
String itemTypeCode = item.getItemTypeCode();
List accountingLines = item.getSourceAccountingLines();
for (Iterator iterator = accountingLines.iterator(); iterator.hasNext();) {
PurApAccountingLine accountingLine = (PurApAccountingLine) iterator.next();
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
if (isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
return false;
}
}
}
return valid;
}
/**
* Validates field requirement by chart for one or multiple system types.
*
* @param systemType
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param parameterName
* @param parameterValueString
* @return
*/
protected boolean validateFieldRequirementByChartForOneOrMultipleSystemType(String systemType, String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String parameterName, String parameterValueString) {
boolean valid = true;
boolean needValidation = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, parameterName, chartCode).evaluationSucceeds());
if (needValidation) {
if (parameterName.startsWith("CHARTS_REQUIRING_LOCATIONS_ADDRESS")) {
return validateCapitalAssetLocationAddressFieldsOneOrMultipleSystemType(capitalAssetSystems);
}
String mappedName = PurapConstants.CAMS_REQUIREDNESS_FIELDS.REQUIREDNESS_FIELDS_BY_PARAMETER_NAMES.get(parameterName);
if (mappedName != null) {
// Check the availability matrix here, if this field doesn't exist according to the avail. matrix, then no need
// to validate any further.
String availableValue = getValueFromAvailabilityMatrix(mappedName, systemType, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
return true;
}
// capitalAssetTransactionType field is off the item
if (mappedName.equals(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE)) {
String[] mappedNames = { PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS, mappedName };
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
valid &= validateFieldRequirementByChartHelper(item, ArrayUtils.subarray(mappedNames, 1, mappedNames.length), keyBuffer, item.getPurchasingItem().getItemLineNumber());
}
}
// all the other fields are off the system.
else {
List<String> mappedNamesList = new ArrayList<String>();
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS);
if (mappedName.indexOf(".") < 0) {
mappedNamesList.add(mappedName);
}
else {
mappedNamesList.addAll(mappedNameSplitter(mappedName));
}
// For One system type, we would only have 1 CapitalAssetSystem, however, for multiple we may have more than
// one systems in the future. Either way, this for loop should allow both the one system and multiple system
// types to work fine.
int count = 0;
for (CapitalAssetSystem system : capitalAssetSystems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[" + new Integer(count) + "].");
valid &= validateFieldRequirementByChartHelper(system, ArrayUtils.subarray(mappedNamesList.toArray(), 1, mappedNamesList.size()), keyBuffer, null);
count++;
}
}
}
}
return valid;
}
/**
* Validates the field requirement by chart for individual system type.
*
* @param systemState
* @param capitalAssetItems
* @param chartCode
* @param parameterName
* @param parameterValueString
* @return
*/
protected boolean validateFieldRequirementByChartForIndividualSystemType(String systemState, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String parameterName, String parameterValueString) {
boolean valid = true;
boolean needValidation = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, parameterName, chartCode).evaluationSucceeds());
if (needValidation) {
if (parameterName.startsWith("CHARTS_REQUIRING_LOCATIONS_ADDRESS")) {
return validateCapitalAssetLocationAddressFieldsForIndividualSystemType(capitalAssetItems);
}
String mappedName = PurapConstants.CAMS_REQUIREDNESS_FIELDS.REQUIREDNESS_FIELDS_BY_PARAMETER_NAMES.get(parameterName);
if (mappedName != null) {
// Check the availability matrix here, if this field doesn't exist according to the avail. matrix, then no need
// to validate any further.
String availableValue = getValueFromAvailabilityMatrix(mappedName, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
return true;
}
// capitalAssetTransactionType field is off the item
List<String> mappedNamesList = new ArrayList<String>();
if (mappedName.equals(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE)) {
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS);
mappedNamesList.add(mappedName);
}
// all the other fields are off the system which is off the item
else {
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS);
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEM);
if (mappedName.indexOf(".") < 0) {
mappedNamesList.add(mappedName);
}
else {
mappedNamesList.addAll(mappedNameSplitter(mappedName));
}
}
// For Individual system type, we'll always iterate through the item, then if the field is off the system, we'll get
// it through
// the purchasingCapitalAssetSystem of the item.
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
valid &= validateFieldRequirementByChartHelper(item, ArrayUtils.subarray(mappedNamesList.toArray(), 1, mappedNamesList.size()), keyBuffer, item.getPurchasingItem().getItemLineNumber());
}
}
}
return valid;
}
/**
* Utility method to split a long String using the "." as the delimiter then add each of the array element into a List of String
* and return the List of String.
*
* @param mappedName The String to be splitted.
* @return The List of String after being splitted, with the "." as delimiter.
*/
protected List<String> mappedNameSplitter(String mappedName) {
List<String> result = new ArrayList<String>();
String[] mappedNamesArray = mappedName.split("\\.");
for (int i = 0; i < mappedNamesArray.length; i++) {
result.add(mappedNamesArray[i]);
}
return result;
}
/**
* Validates the field requirement by chart recursively and give error messages when it returns false.
*
* @param bean The object to be used to obtain the property value
* @param mappedNames The array of Strings which when combined together, they form the field property
* @param errorKey The error key to be used for adding error messages to the error map.
* @param itemNumber The Integer that represents the item number that we're currently iterating.
* @return true if it passes the validation.
*/
protected boolean validateFieldRequirementByChartHelper(Object bean, Object[] mappedNames, StringBuffer errorKey, Integer itemNumber) {
boolean valid = true;
Object value = ObjectUtils.getPropertyValue(bean, (String) mappedNames[0]);
if (ObjectUtils.isNull(value)) {
errorKey.append(mappedNames[0]);
String fieldName = SpringContext.getBean(DataDictionaryService.class).getAttributeErrorLabel(bean.getClass(), (String) mappedNames[0]);
if (itemNumber != null) {
fieldName = fieldName + " in Item " + itemNumber;
}
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, fieldName);
return false;
}
else if (value instanceof Collection) {
if (((Collection) value).isEmpty()) {
// if this collection doesn't contain anything, when it's supposed to contain some strings with values, return
// false.
errorKey.append(mappedNames[0]);
String mappedNameStr = (String) mappedNames[0];
String methodToInvoke = "get" + (mappedNameStr.substring(0, 1)).toUpperCase() + mappedNameStr.substring(1, mappedNameStr.length() - 1) + "Class";
Class offendingClass;
try {
offendingClass = (Class) bean.getClass().getMethod(methodToInvoke, null).invoke(bean, null);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
BusinessObjectEntry boe = SpringContext.getBean(DataDictionaryService.class).getDataDictionary().getBusinessObjectEntry(offendingClass.getSimpleName());
List<AttributeDefinition> offendingAttributes = boe.getAttributes();
AttributeDefinition offendingAttribute = offendingAttributes.get(0);
String fieldName = SpringContext.getBean(DataDictionaryService.class).getAttributeShortLabel(offendingClass, offendingAttribute.getName());
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, fieldName);
return false;
}
int count = 0;
for (Iterator iter = ((Collection) value).iterator(); iter.hasNext();) {
errorKey.append(mappedNames[0] + "[" + count + "].");
count++;
valid &= validateFieldRequirementByChartHelper(iter.next(), ArrayUtils.subarray(mappedNames, 1, mappedNames.length), errorKey, itemNumber);
}
return valid;
}
else if (StringUtils.isBlank(value.toString())) {
errorKey.append(mappedNames[0]);
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, (String) mappedNames[0]);
return false;
}
else if (mappedNames.length > 1) {
// this means we have not reached the end of a single field to be traversed yet, so continue with the recursion.
errorKey.append(mappedNames[0]).append(".");
valid &= validateFieldRequirementByChartHelper(value, ArrayUtils.subarray(mappedNames, 1, mappedNames.length), errorKey, itemNumber);
return valid;
}
else {
return true;
}
}
protected String getValueFromAvailabilityMatrix(String fieldName, String systemType, String systemState) {
for (AvailabilityMatrix am : PurapConstants.CAMS_AVAILABILITY_MATRIX.MATRIX_LIST) {
if (am.fieldName.equals(fieldName) && am.systemState.equals(systemState) && am.systemType.equals(systemType)) {
return am.availableValue;
}
}
// if we can't find any matching from availability matrix, return null for now.
return null;
}
/**
* Validates that the total quantity on all locations equals to the quantity on the line item. This is only used for IND system
* type.
*
* @param capitalAssetItems
* @return true if the total quantity on all locations equals to the quantity on the line item.
*/
protected boolean validateQuantityOnLocationsEqualsQuantityOnItem(List<PurchasingCapitalAssetItem> capitalAssetItems, String systemType, String systemState) {
boolean valid = true;
String availableValue = getValueFromAvailabilityMatrix(PurapPropertyConstants.CAPITAL_ASSET_LOCATIONS + "." + PurapPropertyConstants.QUANTITY, systemType, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
// If the location quantity isn't available on the document given the system type and system state, we don't need to
// validate this, just return true.
return true;
}
int count = 0;
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
if (item.getPurchasingItem() != null && item.getPurchasingItem().getItemType().isQuantityBasedGeneralLedgerIndicator() && !item.getPurchasingCapitalAssetSystem().getCapitalAssetLocations().isEmpty()) {
KualiDecimal total = new KualiDecimal(0);
for (CapitalAssetLocation location : item.getPurchasingCapitalAssetSystem().getCapitalAssetLocations()) {
if (ObjectUtils.isNotNull(location.getItemQuantity())) {
total = total.add(location.getItemQuantity());
}
}
if (!item.getPurchasingItem().getItemQuantity().equals(total)) {
valid = false;
String errorKey = PurapKeyConstants.ERROR_CAPITAL_ASSET_LOCATIONS_QUANTITY_MUST_EQUAL_ITEM_QUANTITY;
String propertyName = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "]." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEM + ".newPurchasingCapitalAssetLocationLine." + PurapPropertyConstants.QUANTITY;
GlobalVariables.getErrorMap().putError(propertyName, errorKey, Integer.toString(count + 1));
}
}
count++;
}
return valid;
}
/**
* Validates for the individual system type that for each of the items, the capitalAssetTransactionTypeCode matches the system
* parameter PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS, the method will return true but if it doesn't match the
* system parameter, then loop through each of the itemCapitalAssets. If there is any non-null capitalAssetNumber then return
* false.
*
* @param capitalAssetItems the List of PurchasingCapitalAssetItems on the document to be validated
* @return false if the capital asset transaction type does not match the system parameter that allows asset numbers but the
* itemCapitalAsset contains at least one asset numbers.
*/
protected boolean validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
int count = 0;
for (PurchasingCapitalAssetItem capitalAssetItem : capitalAssetItems) {
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetItem.getPurchasingCapitalAssetSystem(), capitalAssetItem.getCapitalAssetTransactionTypeCode(), prefix);
count++;
}
return valid;
}
/**
* Generic validation that if the capitalAssetTransactionTypeCode does not match the system parameter
* PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS and at least one of the itemCapitalAssets contain a non-null
* capitalAssetNumber then return false. This method is used by one system and multiple system types as well as being used as a
* helper method for validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers method.
*
* @param capitalAssetSystem the capitalAssetSystem containing a List of itemCapitalAssets to be validated.
* @param capitalAssetTransactionType the capitalAssetTransactionTypeCode containing asset numbers to be validated.
* @return false if the capital asset transaction type does not match the system parameter that allows asset numbers but the
* itemCapitalAsset contains at least one asset numbers.
*/
protected boolean validatePurchasingTransactionTypesAllowingAssetNumbers(CapitalAssetSystem capitalAssetSystem, String capitalAssetTransactionType, String prefix) {
boolean allowedAssetNumbers = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS, capitalAssetTransactionType).evaluationSucceeds());
if (allowedAssetNumbers) {
// If this is a transaction type that allows asset numbers, we don't need to validate anymore, just return true here.
return true;
}
else {
for (ItemCapitalAsset asset : capitalAssetSystem.getItemCapitalAssets()) {
if (asset.getCapitalAssetNumber() != null) {
String propertyName = prefix + PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE;
GlobalVariables.getErrorMap().putError(propertyName, PurapKeyConstants.ERROR_CAPITAL_ASSET_ASSET_NUMBERS_NOT_ALLOWED_TRANS_TYPE, capitalAssetTransactionType);
return false;
}
}
}
return true;
}
/**
* TODO: rename this method removing trade in reference? Validates that if the non quantity drive allowed indicator on the
* capital asset transaction type is false and the item is of non quantity type
*
* @param capitalAssetItems The List of PurchasingCapitalAssetItem to be validated.
* @return false if the indicator is false and there is at least one non quantity items on the list.
*/
protected boolean validateNonQuantityDrivenAllowedIndicatorAndTradeIn(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
int count = 0;
for (PurchasingCapitalAssetItem capitalAssetItem : capitalAssetItems) {
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "].";
if (StringUtils.isNotBlank(capitalAssetItem.getCapitalAssetTransactionTypeCode())) {
// ((PurchasingCapitalAssetItemBase)
// capitalAssetItem).refreshReferenceObject(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE);
if (!capitalAssetItem.getCapitalAssetTransactionType().getCapitalAssetNonquantityDrivenAllowIndicator()) {
if (!capitalAssetItem.getPurchasingItem().getItemType().isQuantityBasedGeneralLedgerIndicator()) {
String propertyName = prefix + PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE;
GlobalVariables.getErrorMap().putError(propertyName, PurapKeyConstants.ERROR_CAPITAL_ASSET_TRANS_TYPE_NOT_ALLOWING_NON_QUANTITY_ITEMS, capitalAssetItem.getCapitalAssetTransactionTypeCode());
valid &= false;
}
}
}
count++;
}
return valid;
}
/**
* Wrapper to do Capital Asset validations, generating errors instead of warnings. Makes sure that the given item's data
* relevant to its later possible classification as a Capital Asset is internally consistent, by marshaling and calling the
* methods marked as Capital Asset validations. This implementation assumes that all object codes are valid (real) object codes.
*
* @param recurringPaymentType The item's document's RecurringPaymentType
* @param item A PurchasingItemBase object
* @param apoCheck True if this check is for APO purposes
* @return True if the item passes all Capital Asset validations
*/
public boolean validateItemCapitalAssetWithErrors(String recurringPaymentTypeCode, ExternalPurApItem item, boolean apoCheck) {
PurchasingItemBase purchasingItem = (PurchasingItemBase) item;
List<String> previousErrorPath = GlobalVariables.getErrorMap().getErrorPath();
GlobalVariables.getErrorMap().clearErrorPath();
GlobalVariables.getErrorMap().addToErrorPath(PurapConstants.CAPITAL_ASSET_TAB_ERRORS);
boolean result = validatePurchasingItemCapitalAsset(recurringPaymentTypeCode, purchasingItem);
// Now that we're done with cams related validations, reset the error path to what it was previously.
GlobalVariables.getErrorMap().clearErrorPath();
for (String path : previousErrorPath) {
GlobalVariables.getErrorMap().addToErrorPath(path);
}
return result;
}
/**
* Makes sure that the given item's data relevant to its later possible classification as a Capital Asset is internally
* consistent, by marshaling and calling the methods marked as Capital Asset validations. This implementation assumes that all
* object codes are valid (real) object codes.
*
* @param recurringPaymentType The item's document's RecurringPaymentType
* @param item A PurchasingItemBase object
* @param warn A boolean which should be set to true if warnings are to be set on the calling document for most of the
* validations, rather than errors.
* @return True if the item passes all Capital Asset validations
*/
protected boolean validatePurchasingItemCapitalAsset(String recurringPaymentTypeCode, PurchasingItem item) {
boolean valid = true;
String capitalAssetTransactionTypeCode = "";
AssetTransactionType capitalAssetTransactionType = null;
String itemIdentifier = item.getItemIdentifierString();
if (item.getPurchasingCapitalAssetItem() != null) {
capitalAssetTransactionTypeCode = item.getPurchasingCapitalAssetItem().getCapitalAssetTransactionTypeCode();
// ((PurchasingCapitalAssetItemBase)
// item.getPurchasingCapitalAssetItem()).refreshReferenceObject(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE);
capitalAssetTransactionType = (AssetTransactionType) item.getPurchasingCapitalAssetItem().getCapitalAssetTransactionType();
}
// These checks do not depend on Accounting Line information, but do depend on transaction type.
if (!StringUtils.isEmpty(capitalAssetTransactionTypeCode)) {
valid &= validateCapitalAssetTransactionTypeVersusRecurrence(capitalAssetTransactionType, recurringPaymentTypeCode, itemIdentifier);
}
return valid &= validatePurapItemCapitalAsset(item, capitalAssetTransactionType);
}
/**
* This method validated purapItem giving a transtype
*
* @param recurringPaymentType
* @param item
* @param warn
* @return
*/
protected boolean validatePurapItemCapitalAsset(PurApItem item, AssetTransactionType capitalAssetTransactionType) {
boolean valid = true;
String itemIdentifier = item.getItemIdentifierString();
boolean quantityBased = item.getItemType().isQuantityBasedGeneralLedgerIndicator();
BigDecimal itemUnitPrice = item.getItemUnitPrice();
HashSet<String> capitalOrExpenseSet = new HashSet<String>(); // For the first validation on every accounting line.
// Do the checks that depend on Accounting Line information.
for (PurApAccountingLine accountingLine : item.getSourceAccountingLines()) {
// Because of ObjectCodeCurrent, we had to refresh this.
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
ObjectCode objectCode = accountingLine.getObjectCode();
String capitalOrExpense = objectCodeCapitalOrExpense(objectCode);
capitalOrExpenseSet.add(capitalOrExpense); // HashSets accumulate distinct values (and nulls) only.
valid &= validateAccountingLinesNotCapitalAndExpense(capitalOrExpenseSet, itemIdentifier, objectCode);
// Do the checks involving capital asset transaction type.
if (capitalAssetTransactionType != null) {
valid &= validateObjectCodeVersusTransactionType(objectCode, capitalAssetTransactionType, itemIdentifier, quantityBased);
}
}
return valid;
}
/**
* Capital Asset validation: An item cannot have among its associated accounting lines both object codes that indicate it is a
* Capital Asset, and object codes that indicate that the item is not a Capital Asset. Whether an object code indicates that the
* item is a Capital Asset is determined by whether its level is among a specific set of levels that are deemed acceptable for
* such items.
*
* @param capitalOrExpenseSet A HashSet containing the distinct values of either "Capital" or "Expense" that have been added to
* it.
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier A String identifying the item for error display
* @param objectCode An ObjectCode, for error display
* @return True if the given HashSet contains at most one of either "Capital" or "Expense"
*/
protected boolean validateAccountingLinesNotCapitalAndExpense(HashSet<String> capitalOrExpenseSet, String itemIdentifier, ObjectCode objectCode) {
boolean valid = true;
// If the set contains more than one distinct string, fail.
if (capitalOrExpenseSet.size() > 1) {
GlobalVariables.getErrorMap().putError(KFSConstants.FINANCIAL_OBJECT_LEVEL_CODE_PROPERTY_NAME, CabKeyConstants.ERROR_ITEM_CAPITAL_AND_EXPENSE, itemIdentifier, objectCode.getFinancialObjectCodeName());
valid &= false;
}
return valid;
}
protected boolean validateLevelCapitalAssetIndication(BigDecimal unitPrice, ObjectCode objectCode, String itemIdentifier) {
String capitalAssetPriceThresholdParam = this.getParameterService().getParameterValue(AssetGlobal.class, CabParameterConstants.CapitalAsset.CAPITALIZATION_LIMIT_AMOUNT);
BigDecimal priceThreshold = null;
try {
priceThreshold = new BigDecimal(capitalAssetPriceThresholdParam);
}
catch (NumberFormatException nfe) {
throw new RuntimeException("the parameter for CAPITAL_ASSET_OBJECT_LEVELS came was not able to be converted to a number.", nfe);
}
if (unitPrice.compareTo(priceThreshold) >= 0) {
List<String> possibleCAMSObjectLevels = this.getParameterService().getParameterValues(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.POSSIBLE_CAPITAL_ASSET_OBJECT_LEVELS);
if (possibleCAMSObjectLevels.contains(objectCode.getFinancialObjectLevelCode())) {
String warning = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(CabKeyConstants.WARNING_ABOVE_THRESHOLD_SUGESTS_CAPITAL_ASSET_LEVEL);
warning = StringUtils.replace(warning, "{0}", itemIdentifier);
warning = StringUtils.replace(warning, "{1}", priceThreshold.toString());
GlobalVariables.getMessageList().add(warning);
return false;
}
}
return true;
}
/**
* Capital Asset validation: If the item has a transaction type, check that the transaction type is acceptable for the object
* code sub-types of all the object codes on the associated accounting lines.
*
* @param objectCode
* @param capitalAssetTransactionType
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier
* @return
*/
protected boolean validateObjectCodeVersusTransactionType(ObjectCode objectCode, CapitalAssetBuilderAssetTransactionType capitalAssetTransactionType, String itemIdentifier, boolean quantityBasedItem) {
boolean valid = true;
String[] objectCodeSubTypes = {};
if (quantityBasedItem) {
String capitalAssetQuantitySubtypeRequiredText = capitalAssetTransactionType.getCapitalAssetQuantitySubtypeRequiredText();
if (capitalAssetQuantitySubtypeRequiredText != null) {
objectCodeSubTypes = StringUtils.split(capitalAssetQuantitySubtypeRequiredText, ";");
}
}
else {
String capitalAssetNonquantitySubtypeRequiredText = capitalAssetTransactionType.getCapitalAssetNonquantitySubtypeRequiredText();
if (capitalAssetNonquantitySubtypeRequiredText != null) {
objectCodeSubTypes = StringUtils.split(capitalAssetNonquantitySubtypeRequiredText, ";");
}
}
boolean found = false;
for (String subType : objectCodeSubTypes) {
if (StringUtils.equals(subType, objectCode.getFinancialObjectSubTypeCode())) {
found = true;
break;
}
}
if (!found) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_TRAN_TYPE_OBJECT_CODE_SUBTYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), objectCode.getFinancialObjectCodeName(), objectCode.getFinancialObjectSubType().getFinancialObjectSubTypeName());
valid &= false;
}
return valid;
}
/**
* Capital Asset validation: If the item has a transaction type, check that if the document specifies that recurring payments
* are to be made, that the transaction type is one that is appropriate for this situation, and that if the document does not
* specify that recurring payments are to be made, that the transaction type is one that is appropriate for that situation.
*
* @param capitalAssetTransactionType
* @param recurringPaymentType
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier
* @return
*/
protected boolean validateCapitalAssetTransactionTypeVersusRecurrence(CapitalAssetBuilderAssetTransactionType capitalAssetTransactionType, String recurringPaymentTypeCode, String itemIdentifier) {
boolean valid = true;
// If there is a tran type ...
if ((capitalAssetTransactionType != null) && (capitalAssetTransactionType.getCapitalAssetTransactionTypeCode() != null)) {
String recurringTransactionTypeCodes = this.getParameterService().getParameterValue(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.RECURRING_CAMS_TRAN_TYPES);
if (StringUtils.isNotEmpty(recurringPaymentTypeCode)) { // If there is a recurring payment type ...
if (!StringUtils.contains(recurringTransactionTypeCodes, capitalAssetTransactionType.getCapitalAssetTransactionTypeCode())) {
// There should be a recurring tran type code.
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_WRONG_TRAN_TYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), CabConstants.ValidationStrings.RECURRING);
valid &= false;
}
}
else { // If the payment type is not recurring ...
// There should not be a recurring transaction type code.
if (StringUtils.contains(recurringTransactionTypeCodes, capitalAssetTransactionType.getCapitalAssetTransactionTypeCode())) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_WRONG_TRAN_TYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), CabConstants.ValidationStrings.NON_RECURRING);
valid &= false;
}
}
}
else { // If there is no transaction type ...
if (StringUtils.isNotEmpty(recurringPaymentTypeCode)) { // If there is a recurring payment type ...
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_NO_TRAN_TYPE, itemIdentifier, CabConstants.ValidationStrings.RECURRING);
valid &= false;
}
else { // If the payment type is not recurring ...
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_NO_TRAN_TYPE, itemIdentifier, CabConstants.ValidationStrings.NON_RECURRING);
valid &= false;
}
}
return valid;
}
/**
* Utility wrapping isCapitalAssetObjectCode for the use of processItemCapitalAssetValidation.
*
* @param oc An ObjectCode
* @return A String indicating that the given object code is either Capital or Expense
*/
protected String objectCodeCapitalOrExpense(ObjectCode oc) {
String capital = CabConstants.ValidationStrings.CAPITAL;
String expense = CabConstants.ValidationStrings.EXPENSE;
return (isCapitalAssetObjectCode(oc) ? capital : expense);
}
/**
* Predicate to determine whether the given object code is of a specified object sub type required for purap cams.
*
* @param oc An ObjectCode
* @return True if the ObjectSubType is the one designated for capital assets.
*/
protected boolean isCapitalAssetObjectCode(ObjectCode oc) {
String capitalAssetObjectSubType = this.getParameterService().getParameterValue(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, PurapParameterConstants.CapitalAsset.PURCHASING_OBJECT_SUB_TYPES);
return (StringUtils.containsIgnoreCase(capitalAssetObjectSubType, oc.getFinancialObjectSubTypeCode()) ? true : false);
}
protected boolean validateCapitalAssetLocationAddressFieldsOneOrMultipleSystemType(List<CapitalAssetSystem> capitalAssetSystems) {
boolean valid = true;
int systemCount = 0;
for (CapitalAssetSystem system : capitalAssetSystems) {
List<CapitalAssetLocation> capitalAssetLocations = system.getCapitalAssetLocations();
StringBuffer errorKey = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[" + new Integer(systemCount++) + "].");
errorKey.append("capitalAssetLocations");
int locationCount = 0;
for (CapitalAssetLocation location : capitalAssetLocations) {
errorKey.append("[" + locationCount++ + "].");
valid &= validateCapitalAssetLocationAddressFields(location, errorKey);
}
}
return valid;
}
protected boolean validateCapitalAssetLocationAddressFieldsForIndividualSystemType(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
CapitalAssetSystem system = item.getPurchasingCapitalAssetSystem();
List<CapitalAssetLocation> capitalAssetLocations = system.getCapitalAssetLocations();
StringBuffer errorKey = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
errorKey.append("purchasingCapitalAssetSystem.capitalAssetLocations");
int i = 0;
for (CapitalAssetLocation location : capitalAssetLocations) {
errorKey.append("[" + i++ + "].");
valid &= validateCapitalAssetLocationAddressFields(location, errorKey);
}
}
return valid;
}
protected boolean validateCapitalAssetLocationAddressFields(CapitalAssetLocation location, StringBuffer errorKey) {
boolean valid = true;
if (StringUtils.isBlank(location.getCapitalAssetLine1Address())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_ADDRESS_LINE1);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetCityName())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_CITY);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetCountryCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_COUNTRY);
valid &= false;
}
else if (location.getCapitalAssetCountryCode().equals(KFSConstants.COUNTRY_CODE_UNITED_STATES)) {
if (StringUtils.isBlank(location.getCapitalAssetStateCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_STATE);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetPostalCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_POSTAL_CODE);
valid &= false;
}
}
if (!location.isOffCampusIndicator()) {
if (StringUtils.isBlank(location.getCampusCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_CAMPUS);
valid &= false;
}
if (StringUtils.isBlank(location.getBuildingCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_BUILDING);
valid &= false;
}
if (StringUtils.isBlank(location.getBuildingRoomNumber())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_ROOM);
valid &= false;
}
}
return valid;
}
protected boolean validateAccountsPayableItem(AccountsPayableItem apItem) {
boolean valid = true;
valid &= validatePurapItemCapitalAsset(apItem, (AssetTransactionType) apItem.getCapitalAssetTransactionType());
return valid;
}
// end of methods for purap
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#validateFinancialProcessingData(org.kuali.kfs.sys.document.AccountingDocument,
* org.kuali.kfs.fp.businessobject.CapitalAssetInformation)
* @param accountingDocument and capitalAssetInformation
* @return True if the FinancialProcessingData is valid.
*/
public boolean validateFinancialProcessingData(AccountingDocument accountingDocument, CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
// Check if we need to collect cams data
String dataEntryExpected = this.getCapitalAssetObjectSubTypeLinesFlag(accountingDocument);
if (StringUtils.isBlank(dataEntryExpected)) {
// Data is not expected
if (!isCapitalAssetInformationBlank(capitalAssetInformation)) {
// If no parameter was found or determined that data shouldn't be collected, give error if data was entered
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_DO_NOT_ENTER_ANY_DATA);
return false;
}
else {
// No data to be collected and no data entered. Hence no error
return true;
}
}
else {
// Data is expected
if (isCapitalAssetInformationBlank(capitalAssetInformation)) {
// No data is entered
if (isCapitalAssetDataRequired(accountingDocument, dataEntryExpected)) {
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_REQUIRE_DATA_ENTRY);
return false;
}
else
return true;
}
else if (!isNewAssetBlank(capitalAssetInformation) && !canCreateNewAsset(accountingDocument, dataEntryExpected)) {
// No allow to create new capital asset
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_QUANTITY, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_UPDATE_ALLOW_ONLY);
return false;
}
else if (!isNewAssetBlank(capitalAssetInformation) && !isUpdateAssetBlank(capitalAssetInformation)) {
// Data exists on both crate new asset and update asset, give error
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_NEW_OR_UPDATE_ONLY);
return false;
}
}
if (!isUpdateAssetBlank(capitalAssetInformation)) {
// Validate update Asset information
valid = validateUpdateCapitalAssetField(capitalAssetInformation, accountingDocument);
}
else {
// Validate New Asset information
valid = checkNewCapitalAssetFieldsExist(capitalAssetInformation);
if (valid) {
valid = validateNewCapitalAssetFields(capitalAssetInformation);
}
}
return valid;
}
/**
* This method...
*
* @param accountingDocument
* @return getCapitalAssetObjectSubTypeLinesFlag = "" ==> no assetObjectSubType code F ==> assetObjectSubType code on source
* lines T ==> assetObjectSubType code on target lines FT ==> assetObjectSubType code on both source and target lines
*/
protected String getCapitalAssetObjectSubTypeLinesFlag(AccountingDocument accountingDocument) {
List<String> financialProcessingCapitalObjectSubTypes = this.getParameterService().getParameterValues(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.FINANCIAL_PROCESSING_CAPITAL_OBJECT_SUB_TYPES);
String getCapitalAssetObjectSubTypeLinesFlag = "";
// Check if SourceAccountingLine has objectSub type code
List<SourceAccountingLine> sAccountingLines = accountingDocument.getSourceAccountingLines();
for (SourceAccountingLine sourceAccountingLine : sAccountingLines) {
ObjectCode objectCode = sourceAccountingLine.getObjectCode();
if (ObjectUtils.isNull(objectCode)) {
break;
}
String objectSubTypeCode = objectCode.getFinancialObjectSubTypeCode();
if (financialProcessingCapitalObjectSubTypes.contains(objectSubTypeCode)) {
getCapitalAssetObjectSubTypeLinesFlag = KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE;
break;
}
}
// Check if TargetAccountingLine has objectSub type code
List<TargetAccountingLine> tAccountingLines = accountingDocument.getTargetAccountingLines();
for (TargetAccountingLine targetAccountingLine : tAccountingLines) {
ObjectCode objectCode = targetAccountingLine.getObjectCode();
if (ObjectUtils.isNull(objectCode)) {
break;
}
String objectSubTypeCode = objectCode.getFinancialObjectSubTypeCode();
if (financialProcessingCapitalObjectSubTypes.contains(objectSubTypeCode)) {
getCapitalAssetObjectSubTypeLinesFlag = getCapitalAssetObjectSubTypeLinesFlag.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE) ? KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE + KFSConstants.TARGET_ACCT_LINE_TYPE_CODE : KFSConstants.TARGET_ACCT_LINE_TYPE_CODE;
break;
}
}
return getCapitalAssetObjectSubTypeLinesFlag;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#hasCapitalAssetObjectSubType(org.kuali.kfs.sys.document.AccountingDocument)
*/
public boolean hasCapitalAssetObjectSubType(AccountingDocument accountingDocument) {
boolean hasCapitalAssetObjectSubType = false;
if (!getCapitalAssetObjectSubTypeLinesFlag(accountingDocument).equals("N"))
hasCapitalAssetObjectSubType = true;
return hasCapitalAssetObjectSubType;
}
/**
* if the capital asset data is required for this transaction
*
* @param accountingDocument and dataEntryExpected
* @return boolean false then the capital asset information is not required
*/
private boolean isCapitalAssetDataRequired(AccountingDocument accountingDocument, String dataEntryExpected) {
boolean isCapitalAssetDataRequired = true;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
// if (isDocumentTypeRestricted(accountingDocument) ||
// accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING)) {
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING)) {
if (dataEntryExpected.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE + KFSConstants.TARGET_ACCT_LINE_TYPE_CODE))
isCapitalAssetDataRequired = false;
}
return isCapitalAssetDataRequired;
}
/**
* if this transaction can create new asset
*
* @param accountingDocument and dataEntryExpected
* @return
*/
private boolean canCreateNewAsset(AccountingDocument accountingDocument, String dataEntryExpected) {
boolean canCreateNewAsset = true;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.CASH_RECEIPT)) {
canCreateNewAsset = false;
}
else {
if (isDocumentTypeRestricted(accountingDocument) && dataEntryExpected.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE))
canCreateNewAsset = false;
}
return canCreateNewAsset;
}
/**
* if this document is restricted
*
* @param accountingDocument
* @return boolean true then this document is restricted
*/
private boolean isDocumentTypeRestricted(AccountingDocument accountingDocument) {
boolean isDocumentTypeRestricted = false;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.GENERAL_ERROR_CORRECTION) || accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.YEAR_END_GENERAL_ERROR_CORRECTION))
isDocumentTypeRestricted = true;
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.DISTRIBUTION_OF_INCOME_AND_EXPENSE) || accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.YEAR_END_DISTRIBUTION_OF_INCOME_AND_EXPENSE))
isDocumentTypeRestricted = true;
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.SERVICE_BILLING))
isDocumentTypeRestricted = true;
return isDocumentTypeRestricted;
}
/**
* To see if capitalAssetInformation is blank
*
* @param capitalAssetInformation
* @return boolean false if the asset is not blank
*/
private boolean isCapitalAssetInformationBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (!isNewAssetBlank(capitalAssetInformation) || !isUpdateAssetBlank(capitalAssetInformation)) {
isBlank = false;
}
return isBlank;
}
/**
* To check if data exists on create new asset
*
* @param capitalAssetInformation
* @return boolean false if the new asset is not blank
*/
private boolean isNewAssetBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetTypeCode()) || ObjectUtils.isNotNull(capitalAssetInformation.getVendorName()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetQuantity()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetManufacturerName()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetManufacturerModelNumber()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetDescription())) {
isBlank = false;
}
return isBlank;
}
/**
* To check if data exists on update asset
*
* @param capitalAssetInformation
* @return boolean false if the update asset is not blank
*/
private boolean isUpdateAssetBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetNumber())) {
isBlank = false;
}
return isBlank;
}
/**
* To validate if the asset is active
*
* @param capitalAssetManagementAsset the asset to be validated
* @return boolean false if the asset is not active
*/
private boolean validateUpdateCapitalAssetField(CapitalAssetInformation capitalAssetInformation, AccountingDocument accountingDocument) {
boolean valid = true;
Map<String, String> params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, capitalAssetInformation.getCapitalAssetNumber().toString());
Asset asset = (Asset) this.getBusinessObjectService().findByPrimaryKey(Asset.class, params);
List<Long> assetNumbers = new ArrayList<Long>();
assetNumbers.add(capitalAssetInformation.getCapitalAssetNumber());
if (ObjectUtils.isNull(asset)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_NUMBER);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, KFSKeyConstants.ERROR_EXISTENCE, label);
}
else if (!(this.getAssetService().isCapitalAsset(asset) && !this.getAssetService().isAssetRetired(asset))) {
// check asset status must be capital asset active.
valid = false;
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_ACTIVE_CAPITAL_ASSET_REQUIRED);
}
else {
String documentNumber = accountingDocument.getDocumentNumber();
String documentType = getDocumentTypeName(accountingDocument);
if (getCapitalAssetManagementModuleService().isFpDocumentEligibleForAssetLock(accountingDocument, documentType) && getCapitalAssetManagementModuleService().isAssetLocked(assetNumbers, documentType, documentNumber)) {
valid = false;
}
}
return valid;
}
/**
* Check if all required fields exist on new asset
*
* @param capitalAssetInformation the fields of add asset to be checked
* @return boolean false if a required field is missing
*/
private boolean checkNewCapitalAssetFieldsExist(CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetTypeCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (capitalAssetInformation.getCapitalAssetQuantity() == null || capitalAssetInformation.getCapitalAssetQuantity() <= 0) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_QUANTITY);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_QUANTITY, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getVendorName())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.VENDOR_NAME);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.VENDOR_NAME, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetManufacturerName())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_MANUFACTURE_NAME);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_MANUFACTURE_NAME, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetDescription())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, CamsPropertyConstants.Asset.CAPITAL_ASSET_DESCRIPTION);
GlobalVariables.getErrorMap().putError(CamsPropertyConstants.Asset.CAPITAL_ASSET_DESCRIPTION, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
int index = 0;
List<CapitalAssetInformationDetail> capitalAssetInformationDetails = capitalAssetInformation.getCapitalAssetInformationDetails();
for (CapitalAssetInformationDetail dtl : capitalAssetInformationDetails) {
String errorPathPrefix = KFSPropertyConstants.DOCUMENT + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION_DETAILS;
if (StringUtils.isBlank(dtl.getCampusCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(Campus.class, KFSPropertyConstants.CAMPUS_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAMPUS_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(dtl.getBuildingCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(Building.class, KFSPropertyConstants.BUILDING_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(dtl.getBuildingRoomNumber())) {
String label = this.getDataDictionaryService().getAttributeLabel(Room.class, KFSPropertyConstants.BUILDING_ROOM_NUMBER);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_ROOM_NUMBER, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
index++;
}
return valid;
}
/**
* To validate new asset information
*
* @param capitalAssetInformation the information of add asset to be validated
* @return boolean false if data is incorrect
*/
private boolean validateNewCapitalAssetFields(CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
Map<String, String> params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, capitalAssetInformation.getCapitalAssetTypeCode().toString());
AssetType assetType = (AssetType) this.getBusinessObjectService().findByPrimaryKey(AssetType.class, params);
if (ObjectUtils.isNull(assetType)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, KFSKeyConstants.ERROR_EXISTENCE, label);
}
int index = 0;
List<CapitalAssetInformationDetail> capitalAssetInformationDetails = capitalAssetInformation.getCapitalAssetInformationDetails();
for (CapitalAssetInformationDetail dtl : capitalAssetInformationDetails) {
// We have to explicitly call this DD service to uppercase each field. This may not be the best place and maybe form
// populate
// is a better place but we CAMS team don't own FP document. This is the best we can do for now.
SpringContext.getBean(BusinessObjectDictionaryService.class).performForceUppercase(dtl);
String errorPathPrefix = KFSPropertyConstants.DOCUMENT + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION_DETAILS;
if (StringUtils.isNotBlank(dtl.getCapitalAssetTagNumber()) && !dtl.getCapitalAssetTagNumber().equalsIgnoreCase(CamsConstants.Asset.NON_TAGGABLE_ASSET)) {
if (isTagNumberDuplicate(capitalAssetInformationDetails, dtl)) {
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAPITAL_ASSET_TAG_NUMBER, CamsKeyConstants.AssetGlobal.ERROR_CAMPUS_TAG_NUMBER_DUPLICATE, dtl.getCapitalAssetTagNumber());
valid = false;
}
}
Map<String, Object> criteria = new HashMap<String, Object>();
criteria.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
Campus campus = (Campus) SpringContext.getBean(KualiModuleService.class).getResponsibleModuleService(Campus.class).getExternalizableBusinessObject(Campus.class, criteria);
if (ObjectUtils.isNull(campus)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(Campus.class, KFSPropertyConstants.CAMPUS_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAMPUS_CODE, KFSKeyConstants.ERROR_EXISTENCE, label);
}
params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
params.put(KFSPropertyConstants.BUILDING_CODE, dtl.getBuildingCode());
Building building = (Building) this.getBusinessObjectService().findByPrimaryKey(Building.class, params);
if (ObjectUtils.isNull(building)) {
valid = false;
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_CODE, CamsKeyConstants.AssetLocationGlobal.ERROR_INVALID_BUILDING_CODE, dtl.getBuildingCode(), dtl.getCampusCode());
}
params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
params.put(KFSPropertyConstants.BUILDING_CODE, dtl.getBuildingCode());
params.put(KFSPropertyConstants.BUILDING_ROOM_NUMBER, dtl.getBuildingRoomNumber());
Room room = (Room) this.getBusinessObjectService().findByPrimaryKey(Room.class, params);
if (ObjectUtils.isNull(room)) {
valid = false;
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_ROOM_NUMBER, CamsKeyConstants.AssetLocationGlobal.ERROR_INVALID_ROOM_NUMBER, dtl.getBuildingRoomNumber(), dtl.getBuildingCode(), dtl.getCampusCode());
}
index++;
}
return valid;
}
/**
* To check if the tag number is duplicate or in use
*
* @param capitalAssetInformation, capitalAssetInformationDetail
* @return boolean false if data is duplicate or in use
*/
private boolean isTagNumberDuplicate(List<CapitalAssetInformationDetail> capitalAssetInformationDetails, CapitalAssetInformationDetail dtl) {
boolean duplicateTag = false;
int tagCounter = 0;
if (!this.getAssetService().findActiveAssetsMatchingTagNumber(dtl.getCapitalAssetTagNumber()).isEmpty()) {
// Tag number is already in use
duplicateTag = true;
}
else {
for (CapitalAssetInformationDetail capitalAssetInfoDetl : capitalAssetInformationDetails) {
if (capitalAssetInfoDetl.getCapitalAssetTagNumber().equalsIgnoreCase(dtl.getCapitalAssetTagNumber().toString())) {
tagCounter++;
}
}
if (tagCounter > 1) {
// Tag number already exists in the collection
duplicateTag = true;
}
}
return duplicateTag;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#notifyRouteStatusChange(java.lang.String,
* java.lang.String)
*/
public void notifyRouteStatusChange(DocumentHeader documentHeader) {
KualiWorkflowDocument workflowDocument = documentHeader.getWorkflowDocument();
String documentNumber = documentHeader.getDocumentNumber();
String documentType = workflowDocument.getDocumentType();
if (workflowDocument.stateIsCanceled() || workflowDocument.stateIsDisapproved()) {
// release CAB line items
activateCabPOLines(documentNumber);
activateCabGlLines(documentNumber);
}
if (workflowDocument.stateIsProcessed()) {
// update CAB GL lines if fully processed
updatePOLinesStatusAsProcessed(documentNumber);
updateGlLinesStatusAsProcessed(documentNumber);
// report asset numbers to PO
Integer poId = getPurchaseOrderIdentifier(documentNumber);
if (poId != null) {
List<Long> assetNumbers = null;
if (DocumentTypeName.ASSET_ADD_GLOBAL.equalsIgnoreCase(documentType)) {
assetNumbers = getAssetNumbersFromAssetGlobal(documentNumber);
}
else if (DocumentTypeName.ASSET_PAYMENT.equalsIgnoreCase(documentType)) {
assetNumbers = getAssetNumbersFromAssetPayment(documentNumber);
}
if (!assetNumbers.isEmpty()) {
String noteText = buildNoteTextForPurApDoc(documentType, assetNumbers);
SpringContext.getBean(PurchasingAccountsPayableModuleService.class).addAssignedAssetNumbers(poId, workflowDocument.getInitiatorPrincipalId(), noteText);
}
}
}
}
/**
* update cab non-PO lines status code for item/account/glEntry to 'P' as fully processed when possible
*
* @param documentNumber
*/
protected void updateGlLinesStatusAsProcessed(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<GeneralLedgerEntryAsset> matchingGlAssets = this.getBusinessObjectService().findMatching(GeneralLedgerEntryAsset.class, fieldValues);
if (matchingGlAssets != null && !matchingGlAssets.isEmpty()) {
for (GeneralLedgerEntryAsset generalLedgerEntryAsset : matchingGlAssets) {
GeneralLedgerEntry generalLedgerEntry = generalLedgerEntryAsset.getGeneralLedgerEntry();
// update gl status as processed
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
this.getBusinessObjectService().save(generalLedgerEntry);
// release asset lock
if (isFpDocumentFullyProcessed(generalLedgerEntry)) {
getCapitalAssetManagementModuleService().deleteAssetLocks(generalLedgerEntry.getDocumentNumber(), null);
}
}
}
}
/**
* Check all generalLedgerEntries from the same FP document are fully processed.
*
* @param generalLedgerEntry
* @return
*/
protected boolean isFpDocumentFullyProcessed(GeneralLedgerEntry generalLedgerEntry) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.GeneralLedgerEntry.DOCUMENT_NUMBER, generalLedgerEntry.getDocumentNumber());
Collection<GeneralLedgerEntry> matchingGlEntries = this.getBusinessObjectService().findMatching(GeneralLedgerEntry.class, fieldValues);
for (GeneralLedgerEntry glEntry : matchingGlEntries) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(glEntry.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* update CAB PO lines status code for item/account/glEntry to 'P' as fully processed when possible
*
* @param documentNumber
*/
protected void updatePOLinesStatusAsProcessed(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingAssets = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
if (matchingAssets != null && !matchingAssets.isEmpty()) {
// Map<Long, GeneralLedgerEntry> updateGlLines = new HashMap<Long, GeneralLedgerEntry>();
// update item and account status code to 'P' as fully processed
for (PurchasingAccountsPayableItemAsset itemAsset : matchingAssets) {
itemAsset.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
for (PurchasingAccountsPayableLineAssetAccount assetAccount : itemAsset.getPurchasingAccountsPayableLineAssetAccounts()) {
assetAccount.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
GeneralLedgerEntry generalLedgerEntry = assetAccount.getGeneralLedgerEntry();
// updateGlLines.put(generalLedgerEntry.getGeneralLedgerAccountIdentifier(), generalLedgerEntry);
if (isGlEntryFullyProcessed(generalLedgerEntry)) {
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
this.getBusinessObjectService().save(generalLedgerEntry);
}
}
// update cab document status code to 'P' as all its items fully processed
PurchasingAccountsPayableDocument purapDocument = itemAsset.getPurchasingAccountsPayableDocument();
if (isDocumentFullyProcessed(purapDocument)) {
purapDocument.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
}
this.getBusinessObjectService().save(purapDocument);
String lockingInformation = null;
PurchaseOrderDocument poDocument = getPurApInfoService().getCurrentDocumentForPurchaseOrderIdentifier(purapDocument.getPurchaseOrderIdentifier());
// Only individual system will lock on item line number. other system will using preq/cm doc nbr as the locking
// key
if (PurapConstants.CapitalAssetTabStrings.INDIVIDUAL_ASSETS.equalsIgnoreCase(poDocument.getCapitalAssetSystemTypeCode())) {
lockingInformation = itemAsset.getAccountsPayableLineItemIdentifier().toString();
}
// release the asset lock no matter if it's Asset global or Asset Payment since the CAB user can create Asset global
// doc even if Purap Asset numbers existing.
if (isAccountsPayableItemLineFullyProcessed(purapDocument, lockingInformation)) {
getCapitalAssetManagementModuleService().deleteAssetLocks(purapDocument.getDocumentNumber(), lockingInformation);
}
}
}
}
/**
* If lockingInformation is not empty, check all item lines from the same PurAp item are fully processed. If lockingInformation
* is empty, we check all items from the same PREQ/CM document processed as fully processed.
*
* @param itemAsset
* @return
*/
protected boolean isAccountsPayableItemLineFullyProcessed(PurchasingAccountsPayableDocument purapDocument, String lockingInformation) {
for (PurchasingAccountsPayableItemAsset item : purapDocument.getPurchasingAccountsPayableItemAssets()) {
if ((StringUtils.isBlank(lockingInformation) && !CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(item.getActivityStatusCode())) || (StringUtils.isNotBlank(lockingInformation) && item.getAccountsPayableLineItemIdentifier().equals(lockingInformation) && !CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(item.getActivityStatusCode()))) {
return false;
}
}
return true;
}
/**
* Check if Gl Entry related accounts are fully processed
*
* @param glEntry
* @return
*/
protected boolean isGlEntryFullyProcessed(GeneralLedgerEntry glEntry) {
for (PurchasingAccountsPayableLineAssetAccount account : glEntry.getPurApLineAssetAccounts()) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equalsIgnoreCase(account.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* Check if PurApDocument related items are fully processed.
*
* @param purapDocument
* @return
*/
protected boolean isDocumentFullyProcessed(PurchasingAccountsPayableDocument purapDocument) {
for (PurchasingAccountsPayableItemAsset item : purapDocument.getPurchasingAccountsPayableItemAssets()) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equalsIgnoreCase(item.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* Build the appropriate note text being set to the purchase order document.
*
* @param documentType
* @param assetNumbers
* @return
*/
private String buildNoteTextForPurApDoc(String documentType, List<Long> assetNumbers) {
StringBuffer noteText = new StringBuffer();
if (DocumentTypeName.ASSET_ADD_GLOBAL.equalsIgnoreCase(documentType)) {
noteText.append("Asset Numbers have been created for this document: ");
}
else {
noteText.append("Existing Asset Numbers have been applied for this document: ");
}
for (int i = 0; i < assetNumbers.size(); i++) {
noteText.append(assetNumbers.get(i).toString());
if (i < assetNumbers.size() - 1) {
noteText.append(", ");
}
}
return noteText.toString();
}
/**
* Acquire asset numbers from CAMS asset payment document.
*
* @param documentNumber
* @param assetNumbers
*/
private List<Long> getAssetNumbersFromAssetGlobal(String documentNumber) {
List<Long> assetNumbers = new ArrayList<Long>();
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CamsPropertyConstants.AssetGlobalDetail.DOCUMENT_NUMBER, documentNumber);
Collection<AssetGlobalDetail> assetGlobalDetails = this.getBusinessObjectService().findMatching(AssetGlobalDetail.class, fieldValues);
for (AssetGlobalDetail detail : assetGlobalDetails) {
assetNumbers.add(detail.getCapitalAssetNumber());
}
return assetNumbers;
}
/**
* Acquire asset numbers from CAMS asset global document.
*
* @param documentNumber
* @param assetNumbers
*/
private List<Long> getAssetNumbersFromAssetPayment(String documentNumber) {
List<Long> assetNumbers = new ArrayList<Long>();
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CamsPropertyConstants.DOCUMENT_NUMBER, documentNumber);
Collection<AssetPaymentAssetDetail> paymentAssetDetails = this.getBusinessObjectService().findMatching(AssetPaymentAssetDetail.class, fieldValues);
for (AssetPaymentAssetDetail detail : paymentAssetDetails) {
if (ObjectUtils.isNotNull(detail.getAsset())) {
assetNumbers.add(detail.getCapitalAssetNumber());
}
}
return assetNumbers;
}
/**
* Query PurchasingAccountsPayableItemAsset and return the purchaseOrderIdentifier if the given documentNumber is initiated from
* the PurAp line.
*
* @param documentNumber
* @return
*/
private Integer getPurchaseOrderIdentifier(String camsDocumentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, camsDocumentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingItems = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
for (PurchasingAccountsPayableItemAsset item : matchingItems) {
if (ObjectUtils.isNull(item.getPurchasingAccountsPayableDocument())) {
item.refreshReferenceObject(CabPropertyConstants.PurchasingAccountsPayableItemAsset.PURCHASING_ACCOUNTS_PAYABLE_DOCUMENT);
}
return item.getPurchasingAccountsPayableDocument().getPurchaseOrderIdentifier();
}
return null;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#getCurrentPurchaseOrderDocumentNumber(java.lang.String)
*/
public String getCurrentPurchaseOrderDocumentNumber(String camsDocumentNumber) {
Integer poId = getPurchaseOrderIdentifier(camsDocumentNumber);
if (poId != null) {
PurchaseOrderDocument poDocument = getPurApInfoService().getCurrentDocumentForPurchaseOrderIdentifier(poId);
if (ObjectUtils.isNotNull(poDocument)) {
return poDocument.getDocumentNumber();
}
}
return null;
}
/**
* Activates CAB GL Lines
*
* @param documentNumber String
*/
protected void activateCabGlLines(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<GeneralLedgerEntryAsset> matchingGlAssets = this.getBusinessObjectService().findMatching(GeneralLedgerEntryAsset.class, fieldValues);
if (matchingGlAssets != null && !matchingGlAssets.isEmpty()) {
for (GeneralLedgerEntryAsset generalLedgerEntryAsset : matchingGlAssets) {
GeneralLedgerEntry generalLedgerEntry = generalLedgerEntryAsset.getGeneralLedgerEntry();
generalLedgerEntry.setTransactionLedgerSubmitAmount(KualiDecimal.ZERO);
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.NEW);
this.getBusinessObjectService().save(generalLedgerEntry);
this.getBusinessObjectService().delete(generalLedgerEntryAsset);
}
}
}
/**
* Activates PO Lines
*
* @param documentNumber String
*/
protected void activateCabPOLines(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingPoAssets = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
if (matchingPoAssets != null && !matchingPoAssets.isEmpty()) {
for (PurchasingAccountsPayableItemAsset itemAsset : matchingPoAssets) {
PurchasingAccountsPayableDocument purapDocument = itemAsset.getPurchasingAccountsPayableDocument();
purapDocument.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(purapDocument);
itemAsset.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(itemAsset);
List<PurchasingAccountsPayableLineAssetAccount> lineAssetAccounts = itemAsset.getPurchasingAccountsPayableLineAssetAccounts();
for (PurchasingAccountsPayableLineAssetAccount assetAccount : lineAssetAccounts) {
assetAccount.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(assetAccount);
GeneralLedgerEntry generalLedgerEntry = assetAccount.getGeneralLedgerEntry();
KualiDecimal submitAmount = generalLedgerEntry.getTransactionLedgerSubmitAmount();
if (submitAmount == null) {
submitAmount = KualiDecimal.ZERO;
}
submitAmount = submitAmount.subtract(assetAccount.getItemAccountTotalAmount());
generalLedgerEntry.setTransactionLedgerSubmitAmount(submitAmount);
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(generalLedgerEntry);
}
}
}
}
/**
* gets the document type based on the instance of a class
*
* @param accountingDocument
* @return
*/
private String getDocumentTypeName(AccountingDocument accountingDocument) {
String documentTypeName = null;
if (accountingDocument instanceof YearEndGeneralErrorCorrectionDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.YEAR_END_GENERAL_ERROR_CORRECTION;
else if (accountingDocument instanceof YearEndDistributionOfIncomeAndExpenseDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.YEAR_END_DISTRIBUTION_OF_INCOME_AND_EXPENSE;
else if (accountingDocument instanceof ServiceBillingDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.SERVICE_BILLING;
else if (accountingDocument instanceof GeneralErrorCorrectionDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.GENERAL_ERROR_CORRECTION;
else if (accountingDocument instanceof CashReceiptDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.CASH_RECEIPT;
else if (accountingDocument instanceof DistributionOfIncomeAndExpenseDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.DISTRIBUTION_OF_INCOME_AND_EXPENSE;
else if (accountingDocument instanceof InternalBillingDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING;
else if (accountingDocument instanceof ProcurementCardDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.PROCUREMENT_CARD;
else
throw new RuntimeException("Invalid FP document type.");
return documentTypeName;
}
public ParameterService getParameterService() {
return SpringContext.getBean(ParameterService.class);
}
public BusinessObjectService getBusinessObjectService() {
return SpringContext.getBean(BusinessObjectService.class);
}
public DataDictionaryService getDataDictionaryService() {
return SpringContext.getBean(DataDictionaryService.class);
}
public AssetService getAssetService() {
return SpringContext.getBean(AssetService.class);
}
public KualiModuleService getKualiModuleService() {
return SpringContext.getBean(KualiModuleService.class);
}
public CapitalAssetManagementModuleService getCapitalAssetManagementModuleService() {
return SpringContext.getBean(CapitalAssetManagementModuleService.class);
}
private PurApInfoService getPurApInfoService() {
return SpringContext.getBean(PurApInfoService.class);
}
}
| KULPURAP-4175: Exception when blanket approving and have blank object code
| work/src/org/kuali/kfs/module/cab/service/impl/CapitalAssetBuilderModuleServiceImpl.java | KULPURAP-4175: Exception when blanket approving and have blank object code | <ide><path>ork/src/org/kuali/kfs/module/cab/service/impl/CapitalAssetBuilderModuleServiceImpl.java
<ide> for (Iterator iterator = accountingLines.iterator(); iterator.hasNext();) {
<ide> PurApAccountingLine accountingLine = (PurApAccountingLine) iterator.next();
<ide> accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
<del> if (isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
<add> if (ObjectUtils.isNotNull(accountingLine.getObjectCode()) && isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
<ide> return true;
<ide> }
<ide> }
<ide> }
<ide> return valid;
<ide> }
<del>
<add>
<ide> /**
<ide> * Validates all the field requirements by chart. It obtains a List of parameters where the parameter names are like
<ide> * "CHARTS_REQUIRING%" then loop through these parameters. If any of the parameter's values is null, then return false
<ide> String documentType = (purchasingDocument instanceof RequisitionDocument) ? "REQUISITION" : "PURCHASE_ORDER";
<ide> boolean valid = true;
<ide> List<Parameter> results = new ArrayList<Parameter>();
<del> Map<String, String> criteria = new HashMap<String, String>();
<add> Map<String,String> criteria = new HashMap<String,String>();
<ide> criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAMESPACE_CODE, CabConstants.Parameters.NAMESPACE);
<ide> criteria.put(CabPropertyConstants.Parameter.PARAMETER_DETAIL_TYPE_CODE, CabConstants.Parameters.DETAIL_TYPE_DOCUMENT);
<ide> criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAME, "CHARTS_REQUIRING%" + documentType);
<ide> results.addAll(SpringContext.getBean(ParameterService.class).retrieveParametersGivenLookupCriteria(criteria));
<ide> for (Parameter parameter : results) {
<ide> if (ObjectUtils.isNotNull(parameter)) {
<del> if (parameter.getParameterValue() != null) {
<add> if (parameter.getParameterValue() != null){
<ide> return false;
<ide> }
<ide> }
<ide> }
<ide> return valid;
<ide> }
<del>
<add>
<ide> /**
<ide> * Validates for PURCHASING_OBJECT_SUB_TYPES parameter. If at least one object code of any accounting line entered is of this
<ide> * type, then return false.
<ide> for (Iterator iterator = accountingLines.iterator(); iterator.hasNext();) {
<ide> PurApAccountingLine accountingLine = (PurApAccountingLine) iterator.next();
<ide> accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
<del> if (isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
<add> if (ObjectUtils.isNotNull(accountingLine.getObjectCode()) && isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
<ide> return false;
<ide> }
<ide> }
<ide> // if this collection doesn't contain anything, when it's supposed to contain some strings with values, return
<ide> // false.
<ide> errorKey.append(mappedNames[0]);
<del> String mappedNameStr = (String) mappedNames[0];
<del> String methodToInvoke = "get" + (mappedNameStr.substring(0, 1)).toUpperCase() + mappedNameStr.substring(1, mappedNameStr.length() - 1) + "Class";
<add> String mappedNameStr = (String)mappedNames[0];
<add> String methodToInvoke = "get" + (mappedNameStr.substring(0, 1)).toUpperCase() + mappedNameStr.substring(1, mappedNameStr.length()-1) + "Class";
<ide> Class offendingClass;
<ide> try {
<del> offendingClass = (Class) bean.getClass().getMethod(methodToInvoke, null).invoke(bean, null);
<add> offendingClass = (Class)bean.getClass().getMethod(methodToInvoke, null).invoke(bean, null);
<ide> }
<ide> catch (Exception ex) {
<ide> throw new RuntimeException(ex);
<ide> // Because of ObjectCodeCurrent, we had to refresh this.
<ide> accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
<ide> ObjectCode objectCode = accountingLine.getObjectCode();
<del> String capitalOrExpense = objectCodeCapitalOrExpense(objectCode);
<del> capitalOrExpenseSet.add(capitalOrExpense); // HashSets accumulate distinct values (and nulls) only.
<del>
<del> valid &= validateAccountingLinesNotCapitalAndExpense(capitalOrExpenseSet, itemIdentifier, objectCode);
<del>
<del>
<del> // Do the checks involving capital asset transaction type.
<del> if (capitalAssetTransactionType != null) {
<del> valid &= validateObjectCodeVersusTransactionType(objectCode, capitalAssetTransactionType, itemIdentifier, quantityBased);
<add>
<add> if(ObjectUtils.isNotNull(objectCode)){
<add> String capitalOrExpense = objectCodeCapitalOrExpense(objectCode);
<add> capitalOrExpenseSet.add(capitalOrExpense); // HashSets accumulate distinct values (and nulls) only.
<add>
<add> valid &= validateAccountingLinesNotCapitalAndExpense(capitalOrExpenseSet, itemIdentifier, objectCode);
<add>
<add>
<add> // Do the checks involving capital asset transaction type.
<add> if (capitalAssetTransactionType != null) {
<add> valid &= validateObjectCodeVersusTransactionType(objectCode, capitalAssetTransactionType, itemIdentifier, quantityBased);
<add> }
<ide> }
<ide> }
<ide> return valid; |
|
Java | apache-2.0 | bd91d11113da836af130bbbe6ef6f65ffa51a8d8 | 0 | yaotj/nutz,elkan1788/nutz,dxxfire/nutz,lzxz1234/nutz,livvyguo/nutz,nutzam/nutz,fengshao0907/nutz,lzxz1234/nutz,fengshao0907/nutz,altihou/nutz,nutzam/nutz,007slm/nutz,QinAIns/nutz,joansmith/nutz,fengshao0907/nutz,lzxz1234/nutz,ywjno/nutz,s24963386/nutz,InsideZhou/nutz,s24963386/nutz,happyday517/nutz,dxxfire/nutz,altihou/nutz,InsideZhou/nutz,joansmith/nutz,007slm/nutz,livvyguo/nutz,sdgdsffdsfff/nutz,ansjsun/nutz,elkan1788/nutz,happyday517/nutz,elkan1788/nutz,elkan1788/nutz,livvyguo/nutz,QinAIns/nutz,ansjsun/nutz,QinAIns/nutz,livvyguo/nutz,nutzam/nutz,ywjno/nutz,lzxz1234/nutz,happyday517/nutz,sdgdsffdsfff/nutz,ywjno/nutz,sunshinefather/nutz,sunshinefather/nutz,altihou/nutz,InsideZhou/nutz,007slm/nutz,fengshao0907/nutz,joansmith/nutz,happyday517/nutz,sunshinefather/nutz,ywjno/nutz,InsideZhou/nutz,altihou/nutz,yaotj/nutz,sdgdsffdsfff/nutz,ansjsun/nutz,sdgdsffdsfff/nutz,nutzam/nutz,ywjno/nutz,dxxfire/nutz,nutzam/nutz,sunshinefather/nutz,ansjsun/nutz,yaotj/nutz,dxxfire/nutz,s24963386/nutz,joansmith/nutz,ansjsun/nutz | package org.nutz.mvc.filter;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.View;
import org.nutz.mvc.view.ServerRedirectView;
/**
* 检查当前 Session,如果存在某一属性,并且不为 null,则通过 <br>
* 否则,返回一个 ServerRecirectView 到对应 path
* <p>
* 构造函数需要两个参数
* <ul>
* <li>第一个是, 需要检查的属性名称。如果 session 里存在这个属性,则表示通过检查
* <li>第二个是,如果未通过检查,将当前请求转向何处。 一个类似 /yourpath/xxx.xx 的路径
* </ul>
*
* @author zozoh([email protected])
*/
public class CheckSession implements ActionFilter {
private String name;
private String path;
public CheckSession(String name, String path) {
this.name = name;
this.path = path;
}
public View match(ActionContext context) {
Object obj = context.getRequest().getSession().getAttribute(name);
if (null == obj)
return new ServerRedirectView(path);
return null;
}
}
| src/org/nutz/mvc/filter/CheckSession.java | package org.nutz.mvc.filter;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.View;
import org.nutz.mvc.view.ServerRedirectView;
/**
* 检查当前 Session,如果存在某一属性,并且不为 null,则通过 <br>
* 否则,返回一个 ServerRecirectView 到对应 path
* <p>
* 构造函数需要两个参数
* <ul>
* <li>第一个是, 需要检查的属性名称。如果 session 里存在这个属性,则表示通过检查
* <li>第二个是,如果未通过检查,将当前请求转向何处。 一个类似 /youpaht/xxx.xx 的路径
* </ul>
*
* @author zozoh([email protected])
*/
public class CheckSession implements ActionFilter {
private String name;
private String path;
public CheckSession(String name, String path) {
this.name = name;
this.path = path;
}
public View match(ActionContext context) {
Object obj = context.getRequest().getSession().getAttribute(name);
if (null == obj)
return new ServerRedirectView(path);
return null;
}
}
| ...
git-svn-id: b73081968da82ba525d2f11eaba64c47babea5dc@1946 423f10f2-e3a4-11dd-a6ea-a32d6b26a33d
| src/org/nutz/mvc/filter/CheckSession.java | ... | <ide><path>rc/org/nutz/mvc/filter/CheckSession.java
<ide> * 构造函数需要两个参数
<ide> * <ul>
<ide> * <li>第一个是, 需要检查的属性名称。如果 session 里存在这个属性,则表示通过检查
<del> * <li>第二个是,如果未通过检查,将当前请求转向何处。 一个类似 /youpaht/xxx.xx 的路径
<add> * <li>第二个是,如果未通过检查,将当前请求转向何处。 一个类似 /yourpath/xxx.xx 的路径
<ide> * </ul>
<ide> *
<ide> * @author zozoh([email protected]) |
|
Java | apache-2.0 | 3796a50c73b6a7174aa61fb098dd2db53369cf40 | 0 | factoryfx/factoryfx,factoryfx/factoryfx,factoryfx/factoryfx,factoryfx/factoryfx | package de.factoryfx.data.attribute.types;
import com.fasterxml.jackson.annotation.JsonCreator;
import de.factoryfx.data.attribute.AttributeMetadata;
import de.factoryfx.data.attribute.ValueListAttribute;
import de.factoryfx.data.jackson.ObservableListJacksonAbleWrapper;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class StringListAttribute extends ValueListAttribute<String> {
public StringListAttribute(AttributeMetadata attributeMetadata) {
super(String.class,attributeMetadata,"empty");
}
@JsonCreator
StringListAttribute(ObservableListJacksonAbleWrapper<String> list) {
super(null,null,null);
set(list.unwrap());
}
public List<String> asUnmodifiableList() {
return Collections.unmodifiableList(get().stream().collect(Collectors.toList()));
}
}
| data/src/main/java/de/factoryfx/data/attribute/types/StringListAttribute.java | package de.factoryfx.data.attribute.types;
import com.fasterxml.jackson.annotation.JsonCreator;
import de.factoryfx.data.attribute.AttributeMetadata;
import de.factoryfx.data.attribute.ValueListAttribute;
import de.factoryfx.data.jackson.ObservableListJacksonAbleWrapper;
public class StringListAttribute extends ValueListAttribute<String> {
public StringListAttribute(AttributeMetadata attributeMetadata) {
super(String.class,attributeMetadata,"empty");
}
@JsonCreator
StringListAttribute(ObservableListJacksonAbleWrapper<String> list) {
super(null,null,null);
set(list.unwrap());
}
}
| add helper method to convert to final list
| data/src/main/java/de/factoryfx/data/attribute/types/StringListAttribute.java | add helper method to convert to final list | <ide><path>ata/src/main/java/de/factoryfx/data/attribute/types/StringListAttribute.java
<ide> import de.factoryfx.data.attribute.AttributeMetadata;
<ide> import de.factoryfx.data.attribute.ValueListAttribute;
<ide> import de.factoryfx.data.jackson.ObservableListJacksonAbleWrapper;
<add>
<add>import java.util.Collections;
<add>import java.util.List;
<add>import java.util.stream.Collectors;
<ide>
<ide> public class StringListAttribute extends ValueListAttribute<String> {
<ide>
<ide> super(null,null,null);
<ide> set(list.unwrap());
<ide> }
<add>
<add> public List<String> asUnmodifiableList() {
<add> return Collections.unmodifiableList(get().stream().collect(Collectors.toList()));
<add> }
<add>
<ide> } |
|
JavaScript | apache-2.0 | 138cddf3d656137abbfbfed8b51aea1e1ac3241f | 0 | GitbookIO/gitbook,ZachLamb/gitbook,vehar/gitbook,justinleoye/gitbook,youprofit/gitbook,switchspan/gitbook,sudobashme/gitbook,2390183798/gitbook,qingying5810/gitbook,gencer/gitbook,yaonphy/SwiftBlog,CN-Sean/gitbook,gaearon/gitbook,gdbooks/gitbook,palerdot/gitbook,JohnTroony/gitbook,megumiteam/documentation,gaearon/gitbook,hongbinz/gitbook,mruse/gitbook,gencer/gitbook,iamchenxin/gitbook,jocr1627/gitbook,JohnTroony/gitbook,grokcoder/gitbook,ferrior30/gitbook,vehar/gitbook,webwlsong/gitbook,a-moses/gitbook,ryanswanson/gitbook,tzq668766/gitbook,haamop/documentation,haamop/documentation,jocr1627/gitbook,bjlxj2008/gitbook,snowsnail/gitbook,alex-dixon/gitbook,OriPekelman/gitbook,wewelove/gitbook,npracht/documentation,xiongjungit/gitbook,tshoper/gitbook,escopecz/documentation,iflyup/gitbook,intfrr/gitbook,iflyup/gitbook,a-moses/gitbook,Abhikos/gitbook,xxxhycl2010/gitbook,npracht/documentation,hongbinz/gitbook,alex-dixon/gitbook,kamyu104/gitbook,thelastmile/gitbook,grokcoder/gitbook,lucciano/gitbook,sudobashme/gitbook,athiruban/gitbook,athiruban/gitbook,guiquanz/gitbook,sunlianghua/gitbook,gdbooks/gitbook,guiquanz/gitbook,mruse/gitbook,snowsnail/gitbook,kamyu104/gitbook,OriPekelman/gitbook,Keystion/gitbook,ferrior30/gitbook,hujianfei1989/gitbook,ZachLamb/gitbook,FKV587/gitbook,CN-Sean/gitbook,xcv58/gitbook,tshoper/gitbook,escopecz/documentation,webwlsong/gitbook,codepiano/gitbook,bjlxj2008/gitbook,rohan07/gitbook,nycitt/gitbook,palerdot/gitbook,mautic/documentation,intfrr/gitbook,qingying5810/gitbook,megumiteam/documentation,lucciano/gitbook,minghe/gitbook,justinleoye/gitbook,shibe97/gitbook,xiongjungit/gitbook,bradparks/gitbook,minghe/gitbook,2390183798/gitbook,boyXiong/gitbook,rohan07/gitbook,codepiano/gitbook,tzq668766/gitbook,bradparks/gitbook,thelastmile/gitbook,hujianfei1989/gitbook,FKV587/gitbook,nycitt/gitbook,xxxhycl2010/gitbook,wewelove/gitbook,xcv58/gitbook,JozoVilcek/gitbook,jasonslyvia/gitbook,boyXiong/gitbook,youprofit/gitbook,mautic/documentation,iamchenxin/gitbook,switchspan/gitbook,jasonslyvia/gitbook,sunlianghua/gitbook,shibe97/gitbook,anrim/gitbook,strawluffy/gitbook | var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var exec = require('child_process').exec;
var fs = require('graceful-fs');
var parse = require("../../parse");
var BaseGenerator = require("../page");
var stringUtils = require("../../utils/string");
var Generator = function() {
BaseGenerator.apply(this, arguments);
};
util.inherits(Generator, BaseGenerator);
Generator.prototype.finish = function() {
var that = this;
return BaseGenerator.prototype.finish.apply(this)
.then(function() {
var d = Q.defer();
var format = that.options.extension || path.extname(that.options.output).replace("\.", "") || "pdf";
if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) {
that.options.cover = path.join(that.options.output, "cover.jpg");
}
var _options = {
"--cover": that.options.cover,
"--title": that.options.title,
"--comments": that.options.description,
"--authors": that.options.author,
"--publisher": "GitBook",
"--chapter": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter ')]",
"--chapter-mark": "pagebreak",
"--page-breaks-before": "/",
"--level1-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-1 ')]",
"--level2-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-2 ')]",
"--level3-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-3 ')]",
"--no-chapters-in-toc": true,
"--max-levels": "1000"
};
if (format == "pdf") {
var pdfOptions = that.options.pdf;
_.extend(_options, {
"--margin-left": String(pdfOptions.margin.left),
"--margin-right": String(pdfOptions.margin.right),
"--margin-top": String(pdfOptions.margin.top),
"--margin-bottom": String(pdfOptions.margin.bottom),
"--pdf-add-toc": Boolean(pdfOptions.toc),
"--pdf-default-font-size": String(pdfOptions.fontSize),
"--pdf-mono-font-size": String(pdfOptions.fontSize),
"--paper-size": String(pdfOptions.paperSize),
"--pdf-page-numbers": Boolean(pdfOptions.pageNumbers),
"--pdf-header-template": String(pdfOptions.headerTemplate),
"--pdf-footer-template": String(pdfOptions.footerTemplate)
});
}
var command = [
"ebook-convert",
path.join(that.options.output, "index.html"),
path.join(that.options.output, "index."+format),
stringUtils.optionsToShellArgs(_options)
].join(" ");
exec(command, function (error, stdout, stderr) {
if (error) {
if (error.code == 127) {
error.message = "Need to install ebook-convert from Calibre";
} else {
error.message = error.message + " "+stdout;
}
return d.reject(error);
}
d.resolve();
});
return d.promise;
});
};
module.exports = Generator;
| lib/generate/ebook/index.js | var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var exec = require('child_process').exec;
var fs = require('graceful-fs');
var parse = require("../../parse");
var BaseGenerator = require("../page");
var stringUtils = require("../../utils/string");
var Generator = function() {
BaseGenerator.apply(this, arguments);
};
util.inherits(Generator, BaseGenerator);
Generator.prototype.finish = function() {
var that = this;
return BaseGenerator.prototype.finish.apply(this)
.then(function() {
var d = Q.defer();
var format = that.options.extension || path.extname(that.options.output).replace("\.", "") || "pdf";
if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) {
that.options.cover = path.join(that.options.output, "cover.jpg");
}
var _options = {
"--cover": that.options.cover,
"--title": that.options.title,
"--comments": that.options.description,
"--authors": that.options.author,
"--chapter": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter ')]",
"--chapter-mark": "pagebreak",
"--page-breaks-before": "/",
"--level1-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-1 ')]",
"--level2-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-2 ')]",
"--level3-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-3 ')]",
"--no-chapters-in-toc": true,
"--max-levels": "1000"
};
if (format == "pdf") {
var pdfOptions = that.options.pdf;
_.extend(_options, {
"--margin-left": String(pdfOptions.margin.left),
"--margin-right": String(pdfOptions.margin.right),
"--margin-top": String(pdfOptions.margin.top),
"--margin-bottom": String(pdfOptions.margin.bottom),
"--pdf-add-toc": Boolean(pdfOptions.toc),
"--pdf-default-font-size": String(pdfOptions.fontSize),
"--pdf-mono-font-size": String(pdfOptions.fontSize),
"--paper-size": String(pdfOptions.paperSize),
"--pdf-page-numbers": Boolean(pdfOptions.pageNumbers),
"--pdf-header-template": String(pdfOptions.headerTemplate),
"--pdf-footer-template": String(pdfOptions.footerTemplate)
});
}
var command = [
"ebook-convert",
path.join(that.options.output, "index.html"),
path.join(that.options.output, "index."+format),
stringUtils.optionsToShellArgs(_options)
].join(" ");
exec(command, function (error, stdout, stderr) {
if (error) {
if (error.code == 127) {
error.message = "Need to install ebook-convert from Calibre";
} else {
error.message = error.message + " "+stdout;
}
return d.reject(error);
}
d.resolve();
});
return d.promise;
});
};
module.exports = Generator;
| Ste GitBook as publisher
| lib/generate/ebook/index.js | Ste GitBook as publisher | <ide><path>ib/generate/ebook/index.js
<ide> "--title": that.options.title,
<ide> "--comments": that.options.description,
<ide> "--authors": that.options.author,
<add> "--publisher": "GitBook",
<ide> "--chapter": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter ')]",
<ide> "--chapter-mark": "pagebreak",
<ide> "--page-breaks-before": "/", |
|
Java | apache-2.0 | 400e421bca14d5ba228a487b9b580dda344c421e | 0 | freiheit-com/wicket,zwsong/wicket,dashorst/wicket,mosoft521/wicket,topicusonderwijs/wicket,bitstorm/wicket,zwsong/wicket,aldaris/wicket,klopfdreh/wicket,Servoy/wicket,aldaris/wicket,aldaris/wicket,mafulafunk/wicket,AlienQueen/wicket,AlienQueen/wicket,martin-g/wicket-osgi,apache/wicket,freiheit-com/wicket,AlienQueen/wicket,freiheit-com/wicket,zwsong/wicket,Servoy/wicket,AlienQueen/wicket,mosoft521/wicket,aldaris/wicket,selckin/wicket,dashorst/wicket,mosoft521/wicket,topicusonderwijs/wicket,bitstorm/wicket,astrapi69/wicket,astrapi69/wicket,Servoy/wicket,AlienQueen/wicket,astrapi69/wicket,topicusonderwijs/wicket,freiheit-com/wicket,topicusonderwijs/wicket,freiheit-com/wicket,bitstorm/wicket,apache/wicket,dashorst/wicket,selckin/wicket,mafulafunk/wicket,selckin/wicket,bitstorm/wicket,klopfdreh/wicket,mafulafunk/wicket,zwsong/wicket,bitstorm/wicket,martin-g/wicket-osgi,Servoy/wicket,selckin/wicket,aldaris/wicket,apache/wicket,martin-g/wicket-osgi,apache/wicket,dashorst/wicket,klopfdreh/wicket,selckin/wicket,klopfdreh/wicket,mosoft521/wicket,mosoft521/wicket,topicusonderwijs/wicket,apache/wicket,Servoy/wicket,dashorst/wicket,astrapi69/wicket,klopfdreh/wicket | /*
* 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.wicket;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import org.apache.wicket.model.IModel;
import org.apache.wicket.resource.loader.IStringResourceLoader;
import org.apache.wicket.settings.IResourceSettings;
import org.apache.wicket.util.concurrent.ConcurrentHashMap;
import org.apache.wicket.util.string.AppendingStringBuffer;
import org.apache.wicket.util.string.interpolator.PropertyVariableInterpolator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A utility class that encapsulates all of the localization related functionality in a way that it
* can be accessed by all areas of the framework in a consistent way. A singleton instance of this
* class is available via the <code>Application</code> object.
* <p>
* You may register additional IStringResourceLoader to extend or replace Wickets default search
* strategy for the properties. E.g. string resource loaders which load the properties from a
* database. There should be no need to extend Localizer.
*
* @see org.apache.wicket.settings.Settings#getLocalizer()
* @see org.apache.wicket.resource.loader.IStringResourceLoader
* @see org.apache.wicket.settings.Settings#getStringResourceLoaders()
*
* @author Chris Turner
* @author Juergen Donnerstag
*/
public class Localizer
{
private static final Logger logger = LoggerFactory.getLogger(Localizer.class);
/** ConcurrentHashMap does not allow null values */
private static final String NULL_VALUE = "<null-value>";
/** Cache properties */
private Map cache = newCache();
/**
* Create the utils instance class backed by the configuration information contained within the
* supplied application object.
*/
public Localizer()
{
}
/**
* Clear all cache entries
*/
public final void clearCache()
{
if (cache != null)
{
cache = new ConcurrentHashMap();
}
}
/**
* @see #getString(String, Component, IModel, Locale, String, String)
*
* @param key
* The key to obtain the resource for
* @param component
* The component to get the resource for
* @return The string resource
* @throws MissingResourceException
* If resource not found and configuration dictates that exception should be thrown
*/
public String getString(final String key, final Component component)
throws MissingResourceException
{
return getString(key, component, null, null);
}
/**
* @see #getString(String, Component, IModel, Locale, String, String)
*
* @param key
* The key to obtain the resource for
* @param component
* The component to get the resource for
* @param model
* The model to use for property substitutions in the strings (optional)
* @return The string resource
* @throws MissingResourceException
* If resource not found and configuration dictates that exception should be thrown
*/
public String getString(final String key, final Component component, final IModel model)
throws MissingResourceException
{
return getString(key, component, model, null);
}
/**
* @see #getString(String, Component, IModel, Locale, String, String)
*
* @param key
* The key to obtain the resource for
* @param component
* The component to get the resource for
* @param defaultValue
* The default value (optional)
* @return The string resource
* @throws MissingResourceException
* If resource not found and configuration dictates that exception should be thrown
*/
public String getString(final String key, final Component component, final String defaultValue)
throws MissingResourceException
{
return getString(key, component, null, defaultValue);
}
/**
* This method is now deprecated.
*
* @param key
* @param component
* @param model
* @param locale
* @param style
* @param defaultValue
* @return String
* @throws MissingResourceException
*
* @Deprecated please use {@link #getString(String, Component, IModel, String)}
*/
public String getString(final String key, final Component component, final IModel model,
final Locale locale, final String style, final String defaultValue)
throws MissingResourceException
{
return getString(key, component, model, defaultValue);
}
/**
* Get the localized string using all of the supplied parameters. This method is left public to
* allow developers full control over string resource loading. However, it is recommended that
* one of the other convenience methods in the class are used as they handle all of the work
* related to obtaining the current user locale and style information.
*
* @param key
* The key to obtain the resource for
* @param component
* The component to get the resource for (optional)
* @param model
* The model to use for substitutions in the strings (optional)
* @param defaultValue
* The default value (optional)
* @return The string resource
* @throws MissingResourceException
* If resource not found and configuration dictates that exception should be thrown
*/
public String getString(final String key, final Component component, final IModel model,
final String defaultValue) throws MissingResourceException
{
final IResourceSettings resourceSettings = Application.get().getResourceSettings();
boolean addedToPage = false;
if (component != null)
{
if ((component instanceof Page) || null != component.findParent(Page.class))
{
addedToPage = true;
}
if (!addedToPage)
{
logger.warn(
"Tried to retrieve a localized string for a component that has not yet been added to the page. "
+ "This can sometimes lead to an invalid or no localized resource returned. "
+ "Make sure you are not calling Component#getString() inside your Component's constructor. "
+ "Offending component: {}", component);
}
}
String cacheKey = null;
String string = null;
// If this component is not yet added to page we do not want to check
// cache as we can generate an invalid cache key
if ((cache != null) && addedToPage)
{
cacheKey = getCacheKey(key, component);
}
// Value not found are cached as well (value = null)
if ((cacheKey != null) && cache.containsKey(cacheKey))
{
string = getFromCache(cacheKey);
}
else
{
// Iterate over all registered string resource loaders until the
// property has been found
Iterator iter = resourceSettings.getStringResourceLoaders().iterator();
while (iter.hasNext())
{
IStringResourceLoader loader = (IStringResourceLoader)iter.next();
string = loader.loadStringResource(component, key);
if (string != null)
{
break;
}
}
// Cache the result incl null if not found
if (cacheKey != null)
{
putIntoCache(cacheKey, string);
}
}
if ((string == null) && (defaultValue != null))
{
// Resource not found, so handle missing resources based on
// application configuration and try the default value
if (resourceSettings.getUseDefaultOnMissingResource())
{
string = defaultValue;
}
}
// If a property value has been found, or a default value was given,
// than replace the placeholder and we are done
if (string != null)
{
return substitutePropertyExpressions(component, string, model);
}
if (resourceSettings.getThrowExceptionOnMissingResource())
{
AppendingStringBuffer message = new AppendingStringBuffer("Unable to find resource: " +
key);
if (component != null)
{
message.append(" for component: ");
message.append(component.getPageRelativePath());
message.append(" [class=").append(component.getClass().getName()).append("]");
}
throw new MissingResourceException(message.toString(), (component != null
? component.getClass().getName() : ""), key);
}
return "[Warning: String resource for '" + key + "' not found]";
}
/**
* Put the value into the cache and associate it with the cache key
*
* @param cacheKey
* @param string
*/
protected void putIntoCache(final String cacheKey, final String string)
{
// ConcurrentHashMap does not allow null values
if (string == null)
{
cache.put(cacheKey, NULL_VALUE);
}
else
{
cache.put(cacheKey, string);
}
}
/**
* Get the value associated with the key from the cache.
*
* @param cacheKey
* @return The value of the key
*/
protected String getFromCache(final String cacheKey)
{
final String value = (String)cache.get(cacheKey);
// ConcurrentHashMap does not allow null values
if (value == NULL_VALUE)
{
return null;
}
else
{
return value;
}
}
/**
* Gets the cache key
*
* @param key
* @param component
* @return The value of the key
*/
protected String getCacheKey(final String key, final Component component)
{
String cacheKey = key;
if (component != null)
{
AppendingStringBuffer buffer = new AppendingStringBuffer(key);
Component cursor = component;
while (cursor != null)
{
buffer.append("-").append(cursor.getClass().getName());
buffer.append(":").append(cursor.getId());
cursor = cursor.getParent();
}
buffer.append("-").append(component.getLocale());
cacheKey = buffer.toString();
}
return cacheKey;
}
/**
* Helper method to handle property variable substitution in strings.
*
* @param component
* The component requesting a model value
* @param string
* The string to substitute into
* @param model
* The model
* @return The resulting string
*/
protected String substitutePropertyExpressions(final Component component, final String string,
final IModel model)
{
if ((string != null) && (model != null))
{
return PropertyVariableInterpolator.interpolate(string, model.getObject());
}
return string;
}
/**
* By default the cache is enabled. Disabling the cache will disable it and clear the cache.
*
* @param value
*/
public final void setEnableCache(boolean value)
{
if (value == false)
{
cache = null;
}
else if (cache == null)
{
cache = newCache();
}
}
/**
* Create a new cache
*
* @return
*/
private Map newCache()
{
return new ConcurrentHashMap();
}
} | jdk-1.4/wicket/src/main/java/org/apache/wicket/Localizer.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.wicket;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import org.apache.wicket.model.IModel;
import org.apache.wicket.resource.loader.IStringResourceLoader;
import org.apache.wicket.settings.IResourceSettings;
import org.apache.wicket.util.concurrent.ConcurrentHashMap;
import org.apache.wicket.util.string.AppendingStringBuffer;
import org.apache.wicket.util.string.interpolator.PropertyVariableInterpolator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A utility class that encapsulates all of the localization related functionality in a way that it
* can be accessed by all areas of the framework in a consistent way. A singleton instance of this
* class is available via the <code>Application</code> object.
* <p>
* You may register additional IStringResourceLoader to extend or replace Wickets default search
* strategy for the properties. E.g. string resource loaders which load the properties from a
* database. There should be no need to extend Localizer.
*
* @see org.apache.wicket.settings.Settings#getLocalizer()
* @see org.apache.wicket.resource.loader.IStringResourceLoader
* @see org.apache.wicket.settings.Settings#getStringResourceLoaders()
*
* @author Chris Turner
* @author Juergen Donnerstag
*/
public class Localizer
{
private static final Logger logger = LoggerFactory.getLogger(Localizer.class);
/** ConcurrentHashMap does not allow null values */
private static final String NULL_VALUE = "<null-value>";
/** Cache properties */
private Map cache = newCache();
/**
* Create the utils instance class backed by the configuration information contained within the
* supplied application object.
*/
public Localizer()
{
}
/**
* Clear all cache entries
*/
public final void clearCache()
{
if (cache != null)
{
cache = new ConcurrentHashMap();
}
}
/**
* @see #getString(String, Component, IModel, Locale, String, String)
*
* @param key
* The key to obtain the resource for
* @param component
* The component to get the resource for
* @return The string resource
* @throws MissingResourceException
* If resource not found and configuration dictates that exception should be thrown
*/
public String getString(final String key, final Component component)
throws MissingResourceException
{
return getString(key, component, null, null);
}
/**
* @see #getString(String, Component, IModel, Locale, String, String)
*
* @param key
* The key to obtain the resource for
* @param component
* The component to get the resource for
* @param model
* The model to use for property substitutions in the strings (optional)
* @return The string resource
* @throws MissingResourceException
* If resource not found and configuration dictates that exception should be thrown
*/
public String getString(final String key, final Component component, final IModel model)
throws MissingResourceException
{
return getString(key, component, model, null);
}
/**
* @see #getString(String, Component, IModel, Locale, String, String)
*
* @param key
* The key to obtain the resource for
* @param component
* The component to get the resource for
* @param defaultValue
* The default value (optional)
* @return The string resource
* @throws MissingResourceException
* If resource not found and configuration dictates that exception should be thrown
*/
public String getString(final String key, final Component component, final String defaultValue)
throws MissingResourceException
{
return getString(key, component, null, defaultValue);
}
/**
* This method is now deprecated.
*
* @param key
* @param component
* @param model
* @param locale
* @param style
* @param defaultValue
* @return String
* @throws MissingResourceException
*
* @Deprecated please use {@link #getString(String, Component, IModel, String)}
*/
public String getString(final String key, final Component component, final IModel model,
final Locale locale, final String style, final String defaultValue)
throws MissingResourceException
{
return getString(key, component, model, defaultValue);
}
/**
* Get the localized string using all of the supplied parameters. This method is left public to
* allow developers full control over string resource loading. However, it is recommended that
* one of the other convenience methods in the class are used as they handle all of the work
* related to obtaining the current user locale and style information.
*
* @param key
* The key to obtain the resource for
* @param component
* The component to get the resource for (optional)
* @param model
* The model to use for substitutions in the strings (optional)
* @param defaultValue
* The default value (optional)
* @return The string resource
* @throws MissingResourceException
* If resource not found and configuration dictates that exception should be thrown
*/
public String getString(final String key, final Component component, final IModel model,
final String defaultValue) throws MissingResourceException
{
final IResourceSettings resourceSettings = Application.get().getResourceSettings();
boolean addedToPage = false;
if (component != null)
{
if ((component instanceof Page) || null != component.findParent(Page.class))
{
addedToPage = true;
}
if (!addedToPage)
{
logger.warn(
"Tried to retrieve a localized string for a component that has not yet been added to the page. "
+ "This can sometimes lead to an invalid or no localized resource returned. "
+ "Make sure you are not calling Component#getString() inside your Component's constructor. "
+ "Offending component: {}", component);
}
}
String cacheKey = null;
String string = null;
// If this component is not yet added to page we do not want to check
// cache as we can generate an invalid cache key
if ((cache != null) && addedToPage)
{
cacheKey = getCacheKey(key, component);
}
// Value not found are cached as well (value = null)
if ((cacheKey != null) && cache.containsKey(cacheKey))
{
string = getFromCache(cacheKey);
}
else
{
// Iterate over all registered string resource loaders until the
// property has been found
Iterator iter = resourceSettings.getStringResourceLoaders().iterator();
while (iter.hasNext())
{
IStringResourceLoader loader = (IStringResourceLoader)iter.next();
string = loader.loadStringResource(component, key);
if (string != null)
{
break;
}
}
// Cache the result incl null if not found
if (cacheKey != null)
{
putIntoCache(cacheKey, string);
}
}
if ((string == null) && (defaultValue != null))
{
// Resource not found, so handle missing resources based on
// application configuration and try the default value
if (resourceSettings.getUseDefaultOnMissingResource())
{
string = defaultValue;
}
}
// If a property value has been found, or a default value was given,
// than replace the placeholder and we are done
if (string != null)
{
return substitutePropertyExpressions(component, string, model);
}
if (resourceSettings.getThrowExceptionOnMissingResource())
{
AppendingStringBuffer message = new AppendingStringBuffer("Unable to find resource: " +
key);
if (component != null)
{
message.append(" for component: ");
message.append(component.getPageRelativePath());
message.append(" [class=").append(component.getClass().getName()).append("]");
}
throw new MissingResourceException(message.toString(), (component != null
? component.getClass().getName() : ""), key);
}
return "[Warning: String resource for '" + key + "' not found]";
}
/**
* Put the value into the cache and associate it with the cache key
*
* @param cacheKey
* @param string
*/
protected void putIntoCache(final String cacheKey, final String string)
{
// ConcurrentHashMap does not allow null values
if (string == null)
{
cache.put(cacheKey, NULL_VALUE);
}
else
{
cache.put(cacheKey, string);
}
}
/**
* Get the value associated with the key from the cache.
*
* @param cacheKey
* @return The value of the key
*/
protected String getFromCache(final String cacheKey)
{
final String value = (String)cache.get(cacheKey);
// ConcurrentHashMap does not allow null values
if (value == NULL_VALUE)
{
return null;
}
else
{
return value;
}
}
/**
* Gets the cache key
*
* @param key
* @param component
* @return The value of the key
*/
protected String getCacheKey(final String key, final Component component)
{
String cacheKey = key;
if (component != null)
{
AppendingStringBuffer buffer = new AppendingStringBuffer(key);
Component cursor = component;
while (cursor != null)
{
buffer.append("-").append(cursor.getClass().getName());
buffer.append(":").append(cursor.getId());
cursor = cursor.getParent();
}
buffer.append("-").append(component.getLocale());
cacheKey = buffer.toString();
}
return cacheKey;
}
/**
* Helper method to handle property variable substitution in strings.
*
* @param component
* The component requesting a model value
* @param string
* The string to substitute into
* @param model
* The model
* @return The resulting string
*/
private String substitutePropertyExpressions(final Component component, final String string,
final IModel model)
{
if ((string != null) && (model != null))
{
return PropertyVariableInterpolator.interpolate(string, model.getObject());
}
return string;
}
/**
* By default the cache is enabled. Disabling the cache will disable it and clear the cache.
*
* @param value
*/
public final void setEnableCache(boolean value)
{
if (value == false)
{
cache = null;
}
else if (cache == null)
{
cache = newCache();
}
}
/**
* Create a new cache
*
* @return
*/
private Map newCache()
{
return new ConcurrentHashMap();
}
} | WICKET-1302 made Localizer.substitutePropertyExpressions() protected
git-svn-id: 5a74b5304d8e7e474561603514f78b697e5d94c4@620190 13f79535-47bb-0310-9956-ffa450edef68
| jdk-1.4/wicket/src/main/java/org/apache/wicket/Localizer.java | WICKET-1302 made Localizer.substitutePropertyExpressions() protected | <ide><path>dk-1.4/wicket/src/main/java/org/apache/wicket/Localizer.java
<ide> * The model
<ide> * @return The resulting string
<ide> */
<del> private String substitutePropertyExpressions(final Component component, final String string,
<add> protected String substitutePropertyExpressions(final Component component, final String string,
<ide> final IModel model)
<ide> {
<ide> if ((string != null) && (model != null)) |
|
Java | lgpl-2.1 | bdcc6b4487313df9d92ff32de74c01d9cace7304 | 0 | MjAbuz/exist,jessealama/exist,ambs/exist,patczar/exist,ljo/exist,MjAbuz/exist,jensopetersen/exist,wshager/exist,dizzzz/exist,dizzzz/exist,ljo/exist,adamretter/exist,zwobit/exist,shabanovd/exist,jensopetersen/exist,jessealama/exist,joewiz/exist,MjAbuz/exist,dizzzz/exist,dizzzz/exist,hungerburg/exist,ambs/exist,ljo/exist,shabanovd/exist,joewiz/exist,RemiKoutcherawy/exist,adamretter/exist,opax/exist,jessealama/exist,hungerburg/exist,zwobit/exist,ljo/exist,patczar/exist,wolfgangmm/exist,patczar/exist,joewiz/exist,patczar/exist,opax/exist,adamretter/exist,hungerburg/exist,jensopetersen/exist,olvidalo/exist,RemiKoutcherawy/exist,ljo/exist,olvidalo/exist,jessealama/exist,lcahlander/exist,kohsah/exist,kohsah/exist,wshager/exist,lcahlander/exist,hungerburg/exist,wolfgangmm/exist,patczar/exist,windauer/exist,eXist-db/exist,windauer/exist,shabanovd/exist,adamretter/exist,MjAbuz/exist,kohsah/exist,opax/exist,MjAbuz/exist,kohsah/exist,joewiz/exist,RemiKoutcherawy/exist,windauer/exist,zwobit/exist,zwobit/exist,windauer/exist,windauer/exist,wolfgangmm/exist,zwobit/exist,dizzzz/exist,kohsah/exist,opax/exist,windauer/exist,jensopetersen/exist,ambs/exist,wshager/exist,RemiKoutcherawy/exist,jessealama/exist,eXist-db/exist,wolfgangmm/exist,jensopetersen/exist,shabanovd/exist,adamretter/exist,ambs/exist,wolfgangmm/exist,eXist-db/exist,jensopetersen/exist,kohsah/exist,RemiKoutcherawy/exist,olvidalo/exist,shabanovd/exist,hungerburg/exist,olvidalo/exist,zwobit/exist,wolfgangmm/exist,eXist-db/exist,adamretter/exist,patczar/exist,eXist-db/exist,lcahlander/exist,MjAbuz/exist,dizzzz/exist,lcahlander/exist,wshager/exist,wshager/exist,RemiKoutcherawy/exist,joewiz/exist,ambs/exist,joewiz/exist,lcahlander/exist,ljo/exist,eXist-db/exist,ambs/exist,opax/exist,jessealama/exist,olvidalo/exist,shabanovd/exist,wshager/exist,lcahlander/exist | /*
* Collection.java - eXist Open Source Native XML Database
* Copyright (C) 2001-03 Wolfgang M. Meier
* [email protected]
* http://exist.sourceforge.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.collections;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.TreeMap;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.log4j.Logger;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.exist.EXistException;
import org.exist.Indexer;
import org.exist.collections.triggers.Trigger;
import org.exist.collections.triggers.TriggerException;
import org.exist.dom.BinaryDocument;
import org.exist.dom.DocumentImpl;
import org.exist.dom.DocumentSet;
import org.exist.security.Group;
import org.exist.security.Permission;
import org.exist.security.PermissionDeniedException;
import org.exist.security.SecurityManager;
import org.exist.security.User;
import org.exist.storage.DBBroker;
import org.exist.storage.cache.Cacheable;
import org.exist.storage.io.VariableByteInput;
import org.exist.storage.io.VariableByteOutputStream;
import org.exist.storage.store.CollectionStore;
import org.exist.util.Configuration;
import org.exist.util.Lock;
import org.exist.util.LockException;
import org.exist.util.ReentrantReadWriteLock;
import org.exist.util.SyntaxException;
import org.exist.util.hashtable.ObjectHashSet;
import org.exist.util.serializer.DOMStreamer;
import org.w3c.dom.Node;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
/**
* This class represents a collection in the database.
*
* A collection maintains a list of sub-collections and documents.
*
* @author wolf
*/
public final class Collection extends Observable
implements Comparable, EntityResolver, Cacheable {
private final static Logger LOG = Logger.getLogger(Collection.class);
private final static String COLLECTION_CONFIG_FILE = "collection.xconf";
private final static int VALIDATION_ENABLED = 0;
private final static int VALIDATION_AUTO = 1;
private final static int VALIDATION_DISABLED = 2;
private int validation = VALIDATION_AUTO;
// the unique internal id to identify this collection
private short collectionId = -1;
// the documents contained in this collection
private Map documents = new TreeMap();
private boolean reloadRequired = false;
// the name of this collection
private String name;
// the permissions assigned to this collection
private Permission permissions = new Permission(0755);
// stores child-collections with their storage address
private ObjectHashSet subcollections = new ObjectHashSet(19);
// temporary field for the storage address
private long address = -1;
// creation time
private long created = 0;
private CatalogResolver resolver;
private List observers = null;
private CollectionConfiguration configuration = null;
private boolean triggersEnabled = true;
// fields required by the collections cache
private int refCount = 0;
private int timestamp = 0;
// the collection store where this collections is stored.
private CollectionStore db;
private Lock lock = null;
public Collection(CollectionStore db, String name) {
this.name = name;
this.db = db;
lock = new ReentrantReadWriteLock(name);
}
public void setName(String name) {
this.name = name;
}
/**
* Add a new sub-collection to the collection.
*
*@param name
*/
public void addCollection(Collection child) {
final int p = child.name.lastIndexOf('/') + 1;
final String childName = child.name.substring(p);
if (!subcollections.contains(childName))
subcollections.add(childName);
}
/**
* Update the specified child-collection.
*
* @param child
*/
public void update(Collection child) {
final int p = child.name.lastIndexOf('/') + 1;
final String childName = child.name.substring(p);
subcollections.remove(childName);
subcollections.add(childName);
}
/**
* Add a document to the collection.
*
*@param doc
*/
public void addDocument(DBBroker broker, DocumentImpl doc) {
if (doc.getDocId() < 0)
doc.setDocId(broker.getNextDocId(this));
documents.put(doc.getFileName(), doc);
}
/**
* Adds a document to the collection, but doesn't keep the document
* object in memory. The collection will be reloaded the first time the
* new document is accessed. Using this method helps to keep memory
* consumption low when loading many documents in a batch.
*
* @param broker
* @param doc
*/
public void addDocumentLink(DBBroker broker, DocumentImpl doc) {
if (doc.getDocId() < 0)
doc.setDocId(broker.getNextDocId(this));
documents.put(doc.getFileName(), null);
reloadRequired = true;
}
/**
* Removes the document from the internal list of resources, but
* doesn't delete the document object itself.
*
* @param doc
*/
public void unlinkDocument(DocumentImpl doc) {
documents.remove(doc.getFileName());
}
/**
* Return an iterator over all subcollections.
*
* The list of subcollections is copied first, so modifications
* via the iterator have no affect.
*
*@return Description of the Return Value
*/
public Iterator collectionIterator() {
try {
lock.acquire(Lock.READ_LOCK);
return subcollections.stableIterator();
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return null;
} finally {
lock.release();
}
}
/**
* Load all collections below this collections
* and return them in a List.
*
* @return List
*/
public List getDescendants(DBBroker broker, User user) {
final ArrayList cl = new ArrayList(subcollections.size());
try {
lock.acquire(Lock.READ_LOCK);
Collection child;
String childName;
for (Iterator i = subcollections.iterator(); i.hasNext(); ) {
childName = (String) i.next();
child = broker.getCollection(name + '/' + childName);
if (permissions.validate(user, Permission.READ)) {
cl.add(child);
if (child.getChildCollectionCount() > 0)
cl.addAll(child.getDescendants(broker, user));
}
}
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
} finally {
lock.release();
}
return cl;
}
/**
* Retrieve all documents contained in this collections.
*
* If recursive is true, documents from sub-collections are
* included.
*
* @param user
* @param recursive
* @return
*/
public DocumentSet allDocs(DBBroker broker, DocumentSet docs,
boolean recursive, boolean checkPermissions) {
if (permissions.validate(broker.getUser(), Permission.READ)) {
getDocuments(broker, docs, checkPermissions);
if (recursive)
allDocs(broker, docs, checkPermissions);
}
return docs;
}
private DocumentSet allDocs(DBBroker broker, DocumentSet docs, boolean checkPermissions) {
try {
lock.acquire(Lock.READ_LOCK);
Collection child;
String childName;
long addr;
for (Iterator i = subcollections.iterator(); i.hasNext(); ) {
childName = (String) i.next();
child = broker.getCollection(name + '/' + childName);
if(child == null) {
LOG.warn("child collection " + childName + " not found. Skipping ...");
// we always check if we have permissions to read the child collection
} else if (child.permissions.validate(broker.getUser(), Permission.READ)) {
child.getDocuments(broker, docs, checkPermissions);
if (child.getChildCollectionCount() > 0)
child.allDocs(broker, docs, checkPermissions);
}
}
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
} finally {
lock.release();
}
return docs;
}
/**
* Add all documents to the specified document set.
*
* @param docs
*/
public DocumentSet getDocuments(DBBroker broker, DocumentSet docs, boolean checkPermissions) {
try {
lock.acquire(Lock.READ_LOCK);
if(reloadRequired) {
broker.reloadCollection(this);
reloadRequired = false;
}
docs.addCollection(this);
docs.addAll(broker, documents.values(), checkPermissions);
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
} finally {
lock.release();
}
return docs;
}
/**
* Check if this collection may be safely removed from the
* cache. Returns false if there are ongoing write operations,
* i.e. one or more of the documents is locked for
* write.
*
* @return
*/
public boolean allowUnload() {
for (Iterator i = documents.values().iterator(); i.hasNext(); ) {
DocumentImpl doc = (DocumentImpl) i.next();
if (doc.isLockedForWrite())
return false;
}
return true;
}
public int compareTo(Object obj) {
Collection other = (Collection) obj;
if (collectionId == other.collectionId)
return 0;
else if (collectionId < other.collectionId)
return -1;
else
return 1;
}
public boolean equals(Object obj) {
if (!(obj instanceof Collection))
return false;
return ((Collection) obj).collectionId == collectionId;
}
/**
* Return the number of child-collections managed by this
* collection.
*
*@return The childCollectionCount value
*/
public int getChildCollectionCount() {
try {
lock.acquire(Lock.READ_LOCK);
return subcollections.size();
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return 0;
} finally {
lock.release();
}
}
/**
* Get a child resource as identified by path. This method doesn't put
* a lock on the document nor does it recognize locks held by other threads.
* There's no guarantee that the document still exists when accessing it.
*
*@param name The name of the document (without collection path)
*@return the document
*/
public DocumentImpl getDocument(DBBroker broker, String name) {
try {
lock.acquire(Lock.READ_LOCK);
if(reloadRequired) {
broker.reloadCollection(this);
reloadRequired = false;
}
DocumentImpl doc = (DocumentImpl) documents.get(name);
if(doc == null)
LOG.debug("Document " + name + " not found!");
return doc;
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return null;
} finally {
lock.release();
}
}
/**
* Retrieve a child resource after putting a read lock on it. With this method,
* access to the received document object is safe.
*
* @param broker
* @param name
* @return
* @throws LockException
*/
public DocumentImpl getDocumentWithLock(DBBroker broker, String name)
throws LockException {
try {
lock.acquire(Lock.READ_LOCK);
if(reloadRequired) {
broker.reloadCollection(this);
reloadRequired = false;
}
DocumentImpl doc = (DocumentImpl) documents.get(name);
Lock updateLock = doc.getUpdateLock();
updateLock.acquire(Lock.READ_LOCK);
return doc;
} finally {
lock.release();
}
}
/**
* Release any locks held on the document.
*
* @param doc
*/
public void releaseDocument(DocumentImpl doc) {
if(doc != null) {
doc.getUpdateLock().release(Lock.READ_LOCK);
}
}
/**
* Returns the number of documents in this collection.
*
*@return The documentCount value
*/
public int getDocumentCount() {
try {
lock.acquire(Lock.READ_LOCK);
return documents.size();
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return 0;
} finally {
lock.release();
}
}
/**
* Get the internal id.
*
*@return The id value
*/
public short getId() {
return collectionId;
}
/**
* Get the name of this collection.
*
*@return The name value
*/
public String getName() {
return name;
}
/**
* Returns the parent-collection.
*
*@return The parent-collection or null if this
*is the root collection.
*/
public Collection getParent(DBBroker broker) {
if (name.equals("/db"))
return null;
String parent = (name.lastIndexOf("/") < 1 ? "/db" : name.substring(0,
name.lastIndexOf("/")));
return broker.getCollection(parent);
}
/**
* Gets the permissions attribute of the Collection object
*
*@return The permissions value
*/
public Permission getPermissions() {
try {
lock.acquire(Lock.READ_LOCK);
return permissions;
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return permissions;
} finally {
lock.release();
}
}
/**
* Check if the collection has a child document.
*
*@param name the name (without path) of the document
*@return
*/
public boolean hasDocument(String name) {
return documents.containsKey(name);
}
/**
* Check if the collection has a sub-collection.
*
*@param name the name of the subcollection (without path).
*@return
*/
public boolean hasSubcollection(String name) {
try {
lock.acquire(Lock.READ_LOCK);
return subcollections.contains(name);
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return subcollections.contains(name);
} finally {
lock.release();
}
}
/**
* Returns an iterator on the child-documents in this collection.
*
*@return
*/
public Iterator iterator(DBBroker broker) {
return getDocuments(broker, new DocumentSet(), false).iterator();
}
/**
* Read collection contents from the stream.
*
* @param istream
* @throws IOException
*/
public void read(DBBroker broker, VariableByteInput istream)
throws IOException {
collectionId = istream.readShort();
final int collLen = istream.readInt();
String sub;
subcollections = new ObjectHashSet(collLen);
for (int i = 0; i < collLen; i++)
subcollections.add(istream.readUTF());
final SecurityManager secman = broker.getBrokerPool()
.getSecurityManager();
final int uid = istream.readInt();
final int gid = istream.readInt();
final int perm = (istream.readByte() & 0777);
if (secman == null) {
permissions.setOwner(SecurityManager.DBA_USER);
permissions.setGroup(SecurityManager.DBA_GROUP);
} else {
permissions.setOwner(secman.getUser(uid));
permissions.setGroup(secman.getGroup(gid).getName());
}
permissions.setPermissions(perm);
created = istream.readLong();
DocumentImpl doc;
byte resourceType;
try {
while (istream.available() > 0) {
resourceType = istream.readByte();
switch (resourceType) {
case DocumentImpl.XML_FILE :
doc = new DocumentImpl(broker, this);
break;
case DocumentImpl.BINARY_FILE :
doc = new BinaryDocument(broker, this);
break;
case -1 :
return; // EOF found
default :
LOG.warn("unknown resource type: " + resourceType);
throw new IOException(
"unable to determine resource type while reading collection "
+ getName());
}
doc.read(istream);
addDocument(broker, doc);
}
} catch (EOFException e) {
}
}
/**
* Remove the specified sub-collection.
*
*@param name Description of the Parameter
*/
public void removeCollection(String name) throws LockException {
try {
lock.acquire(Lock.WRITE_LOCK);
subcollections.remove(name);
} finally {
lock.release();
}
}
/**
* Remove the specified document from the collection.
*
*@param name
*/
public void removeDocument(DBBroker broker, String docname)
throws PermissionDeniedException, TriggerException, LockException {
try {
lock.acquire(Lock.READ_LOCK);
Trigger trigger = null;
if (!docname.equals(COLLECTION_CONFIG_FILE)) {
if (triggersEnabled) {
CollectionConfiguration config = getConfiguration(broker);
if (config != null)
trigger = config
.getTrigger(Trigger.REMOVE_DOCUMENT_EVENT);
}
} else
configuration = null;
DocumentImpl doc = getDocument(broker, docname);
if (doc == null)
return;
if(doc.isLockedForWrite())
throw new PermissionDeniedException("Document " + doc.getFileName() +
" is locked for write");
if (!getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException(
"Write access to collection denied; user=" + broker.getUser().getName());
if (!doc.getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException("Permission to remove document denied");
if (trigger != null && triggersEnabled) {
trigger.prepare(Trigger.REMOVE_DOCUMENT_EVENT, broker, docname,
doc);
}
broker.removeDocument(getName() + '/' + docname);
documents.remove(docname);
broker.saveCollection(this);
} finally {
lock.release();
}
}
public void removeBinaryResource(DBBroker broker,
String docname) throws PermissionDeniedException, LockException {
try {
lock.acquire(Lock.WRITE_LOCK);
DocumentImpl doc = getDocument(broker, docname);
if(doc.isLockedForWrite())
throw new PermissionDeniedException("Document " + doc.getFileName() +
" is locked for write");
if (!getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException(
"write access to collection denied; user=" + broker.getUser().getName());
if (!doc.getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException("permission to remove document denied");
removeBinaryResource(broker, doc);
} finally {
lock.release();
}
}
public void removeBinaryResource(DBBroker broker,
DocumentImpl doc) throws PermissionDeniedException, LockException {
if (doc == null)
return;
if (doc.getResourceType() != DocumentImpl.BINARY_FILE)
throw new PermissionDeniedException("document " + doc.getFileName()
+ " is not a binary object");
if(doc.isLockedForWrite())
throw new PermissionDeniedException("Document " + doc.getFileName() +
" is locked for write");
if (!getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException(
"write access to collection denied; user=" + broker.getUser().getName());
if (!doc.getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException("permission to remove document denied");
try {
lock.acquire(Lock.WRITE_LOCK);
broker.removeBinaryResource((BinaryDocument) doc);
documents.remove(doc.getFileName());
broker.saveCollection(this);
} finally {
lock.release();
}
}
public DocumentImpl addDocument(DBBroker broker, String name, String data)
throws EXistException, PermissionDeniedException, TriggerException,
SAXException, LockException {
return addDocument(broker, name, data, false);
}
public DocumentImpl addDocument(DBBroker broker, String name, String data,
boolean privileged) throws EXistException,
PermissionDeniedException, TriggerException, SAXException,
LockException {
if (broker.isReadOnly())
throw new PermissionDeniedException("Database is read-only");
DocumentImpl document, oldDoc = null;
XMLReader reader;
InputSource source;
try {
oldDoc = checkPermissions(broker, name);
document = new DocumentImpl(broker, name, this);
manageDocumentInformation(broker, name, oldDoc, document );
// setup triggers
Trigger trigger = null;
if (triggersEnabled && !name.equals(COLLECTION_CONFIG_FILE)) {
if (triggersEnabled) {
CollectionConfiguration config = getConfiguration(broker);
if (config != null) {
if (oldDoc == null)
trigger = config
.getTrigger(Trigger.STORE_DOCUMENT_EVENT);
else
trigger = config
.getTrigger(Trigger.UPDATE_DOCUMENT_EVENT);
}
}
} else
// set configuration to null if we are updating collection.xconf
configuration = null;
Indexer indexer = new Indexer(broker);
indexer.setDocument(document);
// add observers to the indexer
Observer observer;
broker.deleteObservers();
if (observers != null) {
for (Iterator i = observers.iterator(); i.hasNext(); ) {
observer = (Observer) i.next();
indexer.addObserver(observer);
broker.addObserver(observer);
}
}
// prepare the SAX parser
indexer.setValidating(true);
reader = getReader(broker);
reader.setEntityResolver(this);
if (trigger != null && triggersEnabled) {
reader.setContentHandler(trigger.getInputHandler());
reader.setProperty(
"http://xml.org/sax/properties/lexical-handler",
trigger.getLexicalInputHandler());
trigger.setOutputHandler(indexer);
trigger.setValidating(true);
// prepare the trigger
trigger.prepare(oldDoc == null
? Trigger.STORE_DOCUMENT_EVENT
: Trigger.UPDATE_DOCUMENT_EVENT, broker, name, oldDoc);
} else {
reader.setContentHandler(indexer);
reader
.setProperty(
"http://xml.org/sax/properties/lexical-handler",
indexer);
}
reader.setErrorHandler(indexer);
// first pass: parse the document to determine tree structure
LOG.debug("validating document " + name);
source = new InputSource(new StringReader(data));
try {
reader.parse(source);
} catch (IOException e) {
throw new EXistException(e);
}
document.setMaxDepth(document.getMaxDepth() + 1);
document.calculateTreeLevelStartPoints();
// new document is valid: remove old document
if (oldDoc != null) {
LOG.debug("removing old document " + oldDoc.getFileName());
if (oldDoc.getResourceType() == DocumentImpl.BINARY_FILE)
broker.removeBinaryResource((BinaryDocument) oldDoc);
else
broker.removeDocument(getName() + '/' + oldDoc.getFileName(), false);
// we continue to use the old document object and just replace its contents
oldDoc.copyOf(document);
indexer.setDocumentObject(oldDoc);
document = oldDoc;
} else {
document.getUpdateLock().acquire(Lock.WRITE_LOCK);
document.setDocId(broker.getNextDocId(this));
}
indexer.setValidating(false);
if (trigger != null)
trigger.setValidating(false);
} catch(EXistException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(SAXException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(PermissionDeniedException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(TriggerException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} finally {
lock.release();
}
// reset the input source
source = new InputSource(new StringReader(data));
// second pass: store the document
LOG.debug("storing document " + document.getDocId() + " ...");
try {
try {
reader.parse(source);
} catch (IOException e) {
throw new EXistException(e);
}
if(oldDoc == null)
addDocument(broker, document);
// broker.checkTree(document);
broker.addDocument(this, document);
broker.closeDocument();
broker.flush();
LOG.debug("document stored.");
// if we are running in privileged mode (e.g. backup/restore)
// notify the SecurityManager about changes
if (getName().equals(SecurityManager.SYSTEM) && document.getFileName().equals(SecurityManager.ACL_FILE)
&& privileged == false) {
// inform the security manager that system data has changed
LOG.debug("users.xml changed");
broker.getBrokerPool().reloadSecurityManager(broker);
}
} finally {
document.getUpdateLock().release(Lock.WRITE_LOCK);
}
broker.deleteObservers();
return document;
}
/** If an old document exists, keep information about the document.
* @param broker
* @param name
* @param oldDoc
* @param document
*/
private void manageDocumentInformation(DBBroker broker, String name, DocumentImpl oldDoc,
DocumentImpl document ) {
if (oldDoc != null) {
document.setCreated(oldDoc.getCreated());
document.setLastModified(System.currentTimeMillis());
document.setPermissions(oldDoc.getPermissions());
} else {
document.setCreated(System.currentTimeMillis());
document.getPermissions().setOwner(broker.getUser());
document.getPermissions().setGroup(
broker.getUser().getPrimaryGroup());
}
}
/** Check Permissions about user and document, and throw exceptions if necessary.
* @param broker
* @param name
* @return
* @throws LockException
* @throws PermissionDeniedException
*/
private DocumentImpl checkPermissions(DBBroker broker, String name) throws LockException, PermissionDeniedException {
DocumentImpl oldDoc = null;
lock.acquire(Lock.WRITE_LOCK);
if (hasDocument(name) && (oldDoc = getDocument(broker, name)) != null) {
// jmv: Note: this was only in addDocument(DBBroker broker, String name, String data,)
if(oldDoc.isLockedForWrite())
throw new PermissionDeniedException("Document " + name +
" is locked for write");
// check if the document is locked by another user
User lockUser = oldDoc.getUserLock();
if(lockUser != null && !lockUser.equals(broker.getUser()))
throw new PermissionDeniedException("The document is locked by user " +
lockUser.getName());
// check if the document is currently being changed by someone else
Lock oldLock = oldDoc.getUpdateLock();
oldLock.acquire(Lock.WRITE_LOCK);
// do we have permissions for update?
if (!oldDoc.getPermissions().validate(broker.getUser(),
Permission.UPDATE))
throw new PermissionDeniedException(
"Document exists and update is not allowed");
if (!(getPermissions().validate(broker.getUser(), Permission.UPDATE) ||
getPermissions().validate(broker.getUser(), Permission.WRITE)))
throw new PermissionDeniedException(
"Document exists and update is not allowed for the collection");
// do we have write permissions?
} else if (!getPermissions().validate(broker.getUser(),
Permission.WRITE))
throw new PermissionDeniedException(
"Not allowed to write to collection " + getName());
return oldDoc;
}
public DocumentImpl addDocument(DBBroker broker, String name,
InputSource source) throws EXistException, LockException,
PermissionDeniedException, TriggerException, SAXException {
return addDocument(broker, name, source, false);
}
public DocumentImpl addDocument(DBBroker broker, String name,
InputSource source, boolean privileged) throws EXistException,
PermissionDeniedException, SAXException, TriggerException,
LockException {
if (broker.isReadOnly())
throw new PermissionDeniedException("Database is read-only");
DocumentImpl document = null, oldDoc = null;
XMLReader reader;
try {
oldDoc = checkPermissions(broker, name);
document = new DocumentImpl(broker, name, this);
manageDocumentInformation(broker, name, oldDoc, document );
// setup triggers
Trigger trigger = null;
if (triggersEnabled && !name.equals(COLLECTION_CONFIG_FILE)) {
if (triggersEnabled) {
CollectionConfiguration config = getConfiguration(broker);
if (config != null) {
if (oldDoc == null)
trigger = config
.getTrigger(Trigger.STORE_DOCUMENT_EVENT);
else
trigger = config
.getTrigger(Trigger.UPDATE_DOCUMENT_EVENT);
}
}
} else
// set configuration to null if we are updating collection.xconf
configuration = null;
Indexer parser = new Indexer(broker);
parser.setDocument(document);
// add observers to the indexer
Observer observer;
broker.deleteObservers();
if (observers != null) {
for (Iterator i = observers.iterator(); i.hasNext(); ) {
observer = (Observer) i.next();
parser.addObserver(observer);
broker.addObserver(observer);
}
}
// prepare the SAX parser
parser.setValidating(true);
reader = getReader(broker);
reader.setEntityResolver(this);
if (trigger != null && triggersEnabled) {
reader.setContentHandler(trigger.getInputHandler());
reader.setProperty(
"http://xml.org/sax/properties/lexical-handler",
trigger.getLexicalInputHandler());
trigger.setOutputHandler(parser);
trigger.setLexicalOutputHandler(parser);
trigger.setValidating(true);
// prepare the trigger
trigger.prepare(oldDoc == null
? Trigger.STORE_DOCUMENT_EVENT
: Trigger.UPDATE_DOCUMENT_EVENT, broker, name, oldDoc);
} else {
reader.setContentHandler(parser);
reader
.setProperty(
"http://xml.org/sax/properties/lexical-handler",
parser);
}
reader.setErrorHandler(parser);
// first pass: parse the document to determine tree structure
LOG.debug("validating document " + name);
try {
reader.parse(source);
} catch (IOException e) {
throw new EXistException(e);
}
document.setMaxDepth(document.getMaxDepth() + 1);//ddddddddddddddddddddddddddddddd
document.calculateTreeLevelStartPoints();
// new document is valid: remove old document
if (oldDoc != null) {
LOG.debug("removing old document " + oldDoc.getFileName());
if (oldDoc.getResourceType() == DocumentImpl.BINARY_FILE)
broker.removeBinaryResource((BinaryDocument) oldDoc);
else
broker.removeDocument(getName() + '/' + oldDoc.getFileName(), false);
oldDoc.copyOf(document);
parser.setDocumentObject(oldDoc);
document = oldDoc;
} else {
document.getUpdateLock().acquire(Lock.WRITE_LOCK);
document.setDocId(broker.getNextDocId(this));
}
parser.setValidating(false);
if (trigger != null)
trigger.setValidating(false);
} catch(EXistException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(SAXException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(PermissionDeniedException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(TriggerException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} finally {
lock.release();
}
// reset the input source
try {
final InputStream is = source.getByteStream();
if (is != null)
is.reset();
else {
final Reader cs = source.getCharacterStream();
if (cs != null)
cs.reset();
}
} catch (IOException e) {
LOG.debug("could not reset input source", e);
}
// second pass: store the document
LOG.debug("storing document ...");
try {
try {
reader.parse(source);
} catch (IOException e) {
throw new EXistException(e);
}
if(oldDoc == null)
addDocument(broker, document);
broker.addDocument(this, document);
broker.closeDocument();
broker.flush();
// if we are running in privileged mode (e.g. backup/restore)
// notify the SecurityManager about changes
if (getName().equals(SecurityManager.SYSTEM) && document.getFileName().equals(SecurityManager.ACL_FILE)
&& privileged == false) {
// inform the security manager that system data has changed
LOG.debug("users.xml changed");
broker.getBrokerPool().reloadSecurityManager(broker);
}
} finally {
document.getUpdateLock().release(Lock.WRITE_LOCK);
}
broker.deleteObservers();
return document;
}
public DocumentImpl addDocument(DBBroker broker, String name, Node node)
throws EXistException, PermissionDeniedException, TriggerException,
SAXException, LockException {
return addDocument(broker, name, node, false);
}
public DocumentImpl addDocument(DBBroker broker, String name, Node node,
boolean privileged) throws EXistException, LockException,
PermissionDeniedException, TriggerException, SAXException {
Indexer parser = new Indexer(broker);
if (broker.isReadOnly())
throw new PermissionDeniedException("Database is read-only");
DocumentImpl document, oldDoc = null;
DOMStreamer streamer;
try {
oldDoc = checkPermissions(broker, name);
document = new DocumentImpl(broker, name, this);
manageDocumentInformation(broker, name, oldDoc, document );
// setup triggers
Trigger trigger = null;
if (triggersEnabled && !name.equals(COLLECTION_CONFIG_FILE)) {
if (triggersEnabled) {
CollectionConfiguration config = getConfiguration(broker);
if (config != null) {
if (oldDoc == null)
trigger = config
.getTrigger(Trigger.STORE_DOCUMENT_EVENT);
else
trigger = config
.getTrigger(Trigger.UPDATE_DOCUMENT_EVENT);
}
}
} else
// set configuration to null if we are updating collection.xconf
configuration = null;
parser.setDocument(document);
// add observers to the indexer
Observer observer;
broker.deleteObservers();
if (observers != null) {
for (Iterator i = observers.iterator(); i.hasNext(); ) {
observer = (Observer) i.next();
parser.addObserver(observer);
broker.addObserver(observer);
}
}
parser.setValidating(true);
streamer = new DOMStreamer();
if (trigger != null && triggersEnabled) {
streamer.setContentHandler(trigger.getInputHandler());
streamer.setLexicalHandler(trigger.getLexicalInputHandler());
trigger.setOutputHandler(parser);
trigger.setValidating(true);
// prepare the trigger
trigger.prepare(oldDoc == null
? Trigger.STORE_DOCUMENT_EVENT
: Trigger.UPDATE_DOCUMENT_EVENT, broker, name, oldDoc);
} else {
streamer.setContentHandler(parser);
streamer.setLexicalHandler(parser);
}
// first pass: parse the document to determine tree structure
LOG.debug("validating document " + name);
streamer.serialize(node, true);
document.setMaxDepth(document.getMaxDepth() + 1);
document.calculateTreeLevelStartPoints();
// new document is valid: remove old document
if (oldDoc != null) {
LOG.debug("removing old document " + oldDoc.getFileName());
if (oldDoc.getResourceType() == DocumentImpl.BINARY_FILE)
broker.removeBinaryResource((BinaryDocument) oldDoc);
else
broker.removeDocument(getName() + '/' + oldDoc.getFileName(), false);
oldDoc.copyOf(document);
parser.setDocumentObject(oldDoc);
document = oldDoc;
} else {
document.getUpdateLock().acquire(Lock.WRITE_LOCK);
document.setDocId(broker.getNextDocId(this));
}
parser.setValidating(false);
if (trigger != null)
trigger.setValidating(false);
} catch(EXistException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(SAXException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(PermissionDeniedException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(TriggerException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} finally {
lock.release();
}
try {
// second pass: store the document
if(LOG.isDebugEnabled())
LOG.debug("storing document " + document.getFileName());
streamer.serialize(node, true);
if(oldDoc == null)
addDocument(broker, document);
broker.addDocument(this, document);
broker.closeDocument();
broker.flush();
// if we are running in privileged mode (e.g. backup/restore)
// notify the SecurityManager about changes
if (getName().equals(SecurityManager.SYSTEM) && document.getFileName().equals(SecurityManager.ACL_FILE)
&& privileged == false) {
// inform the security manager that system data has changed
if(LOG.isDebugEnabled())
LOG.debug("users.xml changed");
broker.getBrokerPool().reloadSecurityManager(broker);
}
} finally {
document.getUpdateLock().release(Lock.WRITE_LOCK);
}
broker.deleteObservers();
return document;
}
public BinaryDocument addBinaryResource(DBBroker broker,
String name, byte[] data) throws EXistException,
PermissionDeniedException, LockException {
if (broker.isReadOnly())
throw new PermissionDeniedException("Database is read-only");
BinaryDocument blob = null;
try {
DocumentImpl oldDoc = checkPermissions(broker, name);
blob = new BinaryDocument(broker, name, this);
manageDocumentInformation(broker, name, oldDoc, blob );
if (oldDoc != null) {
LOG.debug("removing old document " + oldDoc.getFileName());
if (oldDoc instanceof BinaryDocument)
broker.removeBinaryResource((BinaryDocument) oldDoc);
else
broker.removeDocument(getName() + '/' + oldDoc.getFileName());
}
broker.storeBinaryResource(blob, data);
addDocument(broker, blob);
broker.addDocument(this, blob);
broker.closeDocument();
return blob;
} finally {
lock.release();
}
}
public void setId(short id) {
this.collectionId = id;
}
public void setPermissions(int mode) throws LockException {
try {
lock.acquire(Lock.WRITE_LOCK);
permissions.setPermissions(mode);
} finally {
lock.release();
}
}
public void setPermissions(String mode) throws SyntaxException, LockException {
try {
lock.acquire(Lock.WRITE_LOCK);
permissions.setPermissions(mode);
} finally {
lock.release();
}
}
/**
* Set permissions for the collection.
*
* @param permissions
*/
public void setPermissions(Permission permissions) throws LockException {
try {
lock.acquire(Lock.WRITE_LOCK);
this.permissions = permissions;
} finally {
lock.release();
}
}
/**
* Write collection contents to stream.
*
* @param ostream
* @throws IOException
*/
public void write(DBBroker broker, VariableByteOutputStream ostream)
throws IOException {
ostream.writeShort(collectionId);
ostream.writeInt(subcollections.size());
String childColl;
for (Iterator i = subcollections.iterator(); i.hasNext(); ) {
childColl = (String) i.next();
ostream.writeUTF(childColl);
}
org.exist.security.SecurityManager secman = broker.getBrokerPool()
.getSecurityManager();
if (secman == null) {
ostream.writeInt(1);
ostream.writeInt(1);
} else {
User user = secman.getUser(permissions.getOwner());
Group group = secman.getGroup(permissions.getOwnerGroup());
ostream.writeInt(user.getUID());
ostream.writeInt(group.getId());
}
ostream.writeByte((byte) permissions.getPermissions());
ostream.writeLong(created);
if(reloadRequired) {
broker.reloadCollection(this);
reloadRequired = false;
}
DocumentImpl doc;
for (Iterator i = documents.values().iterator(); i.hasNext(); ) {
doc = (DocumentImpl) i.next();
doc.write(ostream);
}
}
private CollectionConfiguration getConfiguration(DBBroker broker) {
if (configuration == null)
configuration = readCollectionConfiguration(broker);
return configuration;
}
private CollectionConfiguration readCollectionConfiguration(DBBroker broker) {
if (hasDocument(COLLECTION_CONFIG_FILE)) {
DocumentImpl doc = getDocument(broker, COLLECTION_CONFIG_FILE);
if(doc == null) {
LOG.warn("collection.xconf exists but could not be loaded");
return null;
}
LOG.debug("found collection.xconf");
triggersEnabled = false;
try {
return new CollectionConfiguration(broker, this, doc);
} catch (CollectionConfigurationException e) {
LOG.warn("Failed to load collection configuration " + e.getMessage());
} finally {
triggersEnabled = true;
}
}
return null;
}
/**
* Set the internal storage address of the collection data.
*
* @param addr
*/
public void setAddress(long addr) {
this.address = addr;
}
public long getAddress() {
return this.address;
}
public void setCreationTime(long ms) {
created = ms;
}
public long getCreationTime() {
return created;
}
public void setTriggersEnabled(boolean enabled) {
try {
lock.acquire(Lock.WRITE_LOCK);
this.triggersEnabled = enabled;
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
this.triggersEnabled = enabled;
} finally {
lock.release();
}
}
private XMLReader getReader(DBBroker broker) throws EXistException,
SAXException {
Configuration config = broker.getConfiguration();
// get validation settings
String option = (String) config.getProperty("indexer.validation");
if (option != null) {
if (option.equals("true"))
validation = VALIDATION_ENABLED;
else if (option.equals("auto"))
validation = VALIDATION_AUTO;
else
validation = VALIDATION_DISABLED;
}
resolver = (CatalogResolver) config.getProperty("resolver");
// create a SAX parser
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
if (validation == VALIDATION_AUTO || validation == VALIDATION_ENABLED)
saxFactory.setValidating(true);
else
saxFactory.setValidating(false);
saxFactory.setNamespaceAware(true);
try {
setFeature(saxFactory,
"http://xml.org/sax/features/namespace-prefixes", true);
setFeature(saxFactory,
"http://apache.org/xml/features/validation/dynamic",
validation == VALIDATION_AUTO);
setFeature(saxFactory,
"http://apache.org/xml/features/validation/schema",
validation == VALIDATION_AUTO
|| validation == VALIDATION_ENABLED);
SAXParser sax = saxFactory.newSAXParser();
XMLReader parser = sax.getXMLReader();
return parser;
} catch (ParserConfigurationException e) {
LOG.warn(e);
throw new EXistException(e);
}
}
/**
* Try to resolve external entities.
*
* This method forwards the request to the resolver. If that fails,
* the method replaces absolute file names with relative ones
* and retries to resolve. This makes it possible to use relative
* file names in the catalog.
*
* @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
*/
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
InputSource is = resolver.resolveEntity(publicId, systemId);
// if resolution failed and publicId == null,
// try to make absolute file names relative and retry
if (is == null) {
if (publicId != null)
return null;
URL url = new URL(systemId);
if (url.getProtocol().equals("file")) {
String path = url.getPath();
File f = new File(path);
if (!f.canRead())
return resolver.resolveEntity(null, f.getName());
else
return new InputSource(f.getAbsolutePath());
} else
return new InputSource(url.openStream());
}
return is;
}
private void setFeature(SAXParserFactory factory, String feature,
boolean value) {
try {
factory.setFeature(feature, value);
} catch (SAXNotRecognizedException e) {
LOG.warn(e);
} catch (SAXNotSupportedException snse) {
LOG.warn(snse);
} catch (ParserConfigurationException pce) {
LOG.warn(pce);
}
}
/* (non-Javadoc)
* @see java.util.Observable#addObserver(java.util.Observer)
*/
public void addObserver(Observer o) {
if (observers == null)
observers = new ArrayList(1);
if (!observers.contains(o))
observers.add(o);
}
/* (non-Javadoc)
* @see java.util.Observable#deleteObservers()
*/
public void deleteObservers() {
if (observers != null)
observers.clear();
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#getKey()
*/
public long getKey() {
return collectionId;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#getReferenceCount()
*/
public int getReferenceCount() {
return refCount;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#incReferenceCount()
*/
public int incReferenceCount() {
return ++refCount;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#decReferenceCount()
*/
public int decReferenceCount() {
return refCount > 0 ? --refCount : 0;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#setReferenceCount(int)
*/
public void setReferenceCount(int count) {
refCount = count;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#setTimestamp(int)
*/
public void setTimestamp(int timestamp) {
this.timestamp = timestamp;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#getTimestamp()
*/
public int getTimestamp() {
return timestamp;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#release()
*/
public boolean sync() {
return false;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#isDirty()
*/
public boolean isDirty() {
return false;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("[");
for(Iterator i = documents.keySet().iterator(); i.hasNext(); ) {
buf.append(i.next());
if(i.hasNext())
buf.append(", ");
}
buf.append("]");
return buf.toString();
}
}
| src/org/exist/collections/Collection.java | /*
* Collection.java - eXist Open Source Native XML Database
* Copyright (C) 2001-03 Wolfgang M. Meier
* [email protected]
* http://exist.sourceforge.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.collections;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.TreeMap;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.log4j.Logger;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.exist.EXistException;
import org.exist.Indexer;
import org.exist.collections.triggers.Trigger;
import org.exist.collections.triggers.TriggerException;
import org.exist.dom.BinaryDocument;
import org.exist.dom.DocumentImpl;
import org.exist.dom.DocumentSet;
import org.exist.security.Group;
import org.exist.security.Permission;
import org.exist.security.PermissionDeniedException;
import org.exist.security.SecurityManager;
import org.exist.security.User;
import org.exist.storage.DBBroker;
import org.exist.storage.cache.Cacheable;
import org.exist.storage.io.VariableByteInput;
import org.exist.storage.io.VariableByteOutputStream;
import org.exist.storage.store.CollectionStore;
import org.exist.util.Configuration;
import org.exist.util.Lock;
import org.exist.util.LockException;
import org.exist.util.ReentrantReadWriteLock;
import org.exist.util.SyntaxException;
import org.exist.util.hashtable.ObjectHashSet;
import org.exist.util.serializer.DOMStreamer;
import org.w3c.dom.Node;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
/**
* This class represents a collection in the database.
*
* A collection maintains a list of sub-collections and documents.
*
* @author wolf
*/
public final class Collection extends Observable
implements Comparable, EntityResolver, Cacheable {
private final static Logger LOG = Logger.getLogger(Collection.class);
private final static String COLLECTION_CONFIG_FILE = "collection.xconf";
private final static int VALIDATION_ENABLED = 0;
private final static int VALIDATION_AUTO = 1;
private final static int VALIDATION_DISABLED = 2;
private int validation = VALIDATION_AUTO;
// the unique internal id to identify this collection
private short collectionId = -1;
// the documents contained in this collection
private Map documents = new TreeMap();
private boolean reloadRequired = false;
// the name of this collection
private String name;
// the permissions assigned to this collection
private Permission permissions = new Permission(0755);
// stores child-collections with their storage address
private ObjectHashSet subcollections = new ObjectHashSet(19);
// temporary field for the storage address
private long address = -1;
// creation time
private long created = 0;
private CatalogResolver resolver;
private List observers = null;
private CollectionConfiguration configuration = null;
private boolean triggersEnabled = true;
// fields required by the collections cache
private int refCount = 0;
private int timestamp = 0;
// the collection store where this collections is stored.
private CollectionStore db;
private Lock lock = null;
public Collection(CollectionStore db, String name) {
this.name = name;
this.db = db;
lock = new ReentrantReadWriteLock(name);
}
public void setName(String name) {
this.name = name;
}
/**
* Add a new sub-collection to the collection.
*
*@param name
*/
public void addCollection(Collection child) {
final int p = child.name.lastIndexOf('/') + 1;
final String childName = child.name.substring(p);
if (!subcollections.contains(childName))
subcollections.add(childName);
}
/**
* Update the specified child-collection.
*
* @param child
*/
public void update(Collection child) {
final int p = child.name.lastIndexOf('/') + 1;
final String childName = child.name.substring(p);
subcollections.remove(childName);
subcollections.add(childName);
}
/**
* Add a document to the collection.
*
*@param doc
*/
public void addDocument(DBBroker broker, DocumentImpl doc) {
if (doc.getDocId() < 0)
doc.setDocId(broker.getNextDocId(this));
documents.put(doc.getFileName(), doc);
}
/**
* Adds a document to the collection, but doesn't keep the document
* object in memory. The collection will be reloaded the first time the
* new document is accessed. Using this method helps to keep memory
* consumption low when loading many documents in a batch.
*
* @param broker
* @param doc
*/
public void addDocumentLink(DBBroker broker, DocumentImpl doc) {
if (doc.getDocId() < 0)
doc.setDocId(broker.getNextDocId(this));
documents.put(doc.getFileName(), null);
reloadRequired = true;
}
/**
* Removes the document from the internal list of resources, but
* doesn't delete the document object itself.
*
* @param doc
*/
public void unlinkDocument(DocumentImpl doc) {
documents.remove(doc.getFileName());
}
/**
* Return an iterator over all subcollections.
*
* The list of subcollections is copied first, so modifications
* via the iterator have no affect.
*
*@return Description of the Return Value
*/
public Iterator collectionIterator() {
try {
lock.acquire(Lock.READ_LOCK);
return subcollections.stableIterator();
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return null;
} finally {
lock.release();
}
}
/**
* Load all collections below this collections
* and return them in a List.
*
* @return List
*/
public List getDescendants(DBBroker broker, User user) {
final ArrayList cl = new ArrayList(subcollections.size());
try {
lock.acquire(Lock.READ_LOCK);
Collection child;
String childName;
for (Iterator i = subcollections.iterator(); i.hasNext(); ) {
childName = (String) i.next();
child = broker.getCollection(name + '/' + childName);
if (permissions.validate(user, Permission.READ)) {
cl.add(child);
if (child.getChildCollectionCount() > 0)
cl.addAll(child.getDescendants(broker, user));
}
}
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
} finally {
lock.release();
}
return cl;
}
/**
* Retrieve all documents contained in this collections.
*
* If recursive is true, documents from sub-collections are
* included.
*
* @param user
* @param recursive
* @return
*/
public DocumentSet allDocs(DBBroker broker, DocumentSet docs,
boolean recursive, boolean checkPermissions) {
if (permissions.validate(broker.getUser(), Permission.READ)) {
getDocuments(broker, docs, checkPermissions);
if (recursive)
allDocs(broker, docs, checkPermissions);
}
return docs;
}
private DocumentSet allDocs(DBBroker broker, DocumentSet docs, boolean checkPermissions) {
try {
lock.acquire(Lock.READ_LOCK);
Collection child;
String childName;
long addr;
for (Iterator i = subcollections.iterator(); i.hasNext(); ) {
childName = (String) i.next();
child = broker.getCollection(name + '/' + childName);
if(child == null) {
LOG.warn("child collection " + childName + " not found. Skipping ...");
// we always check if we have permissions to read the child collection
} else if (child.permissions.validate(broker.getUser(), Permission.READ)) {
child.getDocuments(broker, docs, checkPermissions);
if (child.getChildCollectionCount() > 0)
child.allDocs(broker, docs, checkPermissions);
}
}
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
} finally {
lock.release();
}
return docs;
}
/**
* Add all documents to the specified document set.
*
* @param docs
*/
public DocumentSet getDocuments(DBBroker broker, DocumentSet docs, boolean checkPermissions) {
try {
lock.acquire(Lock.READ_LOCK);
if(reloadRequired) {
broker.reloadCollection(this);
reloadRequired = false;
}
docs.addCollection(this);
docs.addAll(broker, documents.values(), checkPermissions);
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
} finally {
lock.release();
}
return docs;
}
/**
* Check if this collection may be safely removed from the
* cache. Returns false if there are ongoing write operations,
* i.e. one or more of the documents is locked for
* write.
*
* @return
*/
public boolean allowUnload() {
for (Iterator i = documents.values().iterator(); i.hasNext(); ) {
DocumentImpl doc = (DocumentImpl) i.next();
if (doc.isLockedForWrite())
return false;
}
return true;
}
public int compareTo(Object obj) {
Collection other = (Collection) obj;
if (collectionId == other.collectionId)
return 0;
else if (collectionId < other.collectionId)
return -1;
else
return 1;
}
public boolean equals(Object obj) {
if (!(obj instanceof Collection))
return false;
return ((Collection) obj).collectionId == collectionId;
}
/**
* Return the number of child-collections managed by this
* collection.
*
*@return The childCollectionCount value
*/
public int getChildCollectionCount() {
try {
lock.acquire(Lock.READ_LOCK);
return subcollections.size();
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return 0;
} finally {
lock.release();
}
}
/**
* Get a child resource as identified by path. This method doesn't put
* a lock on the document nor does it recognize locks held by other threads.
* There's no guarantee that the document still exists when accessing it.
*
*@param name The name of the document (without collection path)
*@return the document
*/
public DocumentImpl getDocument(DBBroker broker, String name) {
try {
lock.acquire(Lock.READ_LOCK);
if(reloadRequired) {
broker.reloadCollection(this);
reloadRequired = false;
}
DocumentImpl doc = (DocumentImpl) documents.get(name);
if(doc == null)
LOG.debug("Document " + name + " not found!");
return doc;
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return null;
} finally {
lock.release();
}
}
/**
* Retrieve a child resource after putting a read lock on it. With this method,
* access to the received document object is safe.
*
* @param broker
* @param name
* @return
* @throws LockException
*/
public DocumentImpl getDocumentWithLock(DBBroker broker, String name)
throws LockException {
try {
lock.acquire(Lock.READ_LOCK);
if(reloadRequired) {
broker.reloadCollection(this);
reloadRequired = false;
}
DocumentImpl doc = (DocumentImpl) documents.get(name);
Lock updateLock = doc.getUpdateLock();
updateLock.acquire(Lock.READ_LOCK);
return doc;
} finally {
lock.release();
}
}
/**
* Release any locks held on the document.
*
* @param doc
*/
public void releaseDocument(DocumentImpl doc) {
if(doc != null) {
doc.getUpdateLock().release(Lock.READ_LOCK);
}
}
/**
* Returns the number of documents in this collection.
*
*@return The documentCount value
*/
public int getDocumentCount() {
try {
lock.acquire(Lock.READ_LOCK);
return documents.size();
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return 0;
} finally {
lock.release();
}
}
/**
* Get the internal id.
*
*@return The id value
*/
public short getId() {
return collectionId;
}
/**
* Get the name of this collection.
*
*@return The name value
*/
public String getName() {
return name;
}
/**
* Returns the parent-collection.
*
*@return The parent-collection or null if this
*is the root collection.
*/
public Collection getParent(DBBroker broker) {
if (name.equals("/db"))
return null;
String parent = (name.lastIndexOf("/") < 1 ? "/db" : name.substring(0,
name.lastIndexOf("/")));
return broker.getCollection(parent);
}
/**
* Gets the permissions attribute of the Collection object
*
*@return The permissions value
*/
public Permission getPermissions() {
try {
lock.acquire(Lock.READ_LOCK);
return permissions;
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return permissions;
} finally {
lock.release();
}
}
/**
* Check if the collection has a child document.
*
*@param name the name (without path) of the document
*@return
*/
public boolean hasDocument(String name) {
return documents.containsKey(name);
}
/**
* Check if the collection has a sub-collection.
*
*@param name the name of the subcollection (without path).
*@return
*/
public boolean hasSubcollection(String name) {
try {
lock.acquire(Lock.READ_LOCK);
return subcollections.contains(name);
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
return subcollections.contains(name);
} finally {
lock.release();
}
}
/**
* Returns an iterator on the child-documents in this collection.
*
*@return
*/
public Iterator iterator(DBBroker broker) {
return getDocuments(broker, new DocumentSet(), false).iterator();
}
/**
* Read collection contents from the stream.
*
* @param istream
* @throws IOException
*/
public void read(DBBroker broker, VariableByteInput istream)
throws IOException {
collectionId = istream.readShort();
final int collLen = istream.readInt();
String sub;
subcollections = new ObjectHashSet(collLen);
for (int i = 0; i < collLen; i++)
subcollections.add(istream.readUTF());
final SecurityManager secman = broker.getBrokerPool()
.getSecurityManager();
final int uid = istream.readInt();
final int gid = istream.readInt();
final int perm = (istream.readByte() & 0777);
if (secman == null) {
permissions.setOwner(SecurityManager.DBA_USER);
permissions.setGroup(SecurityManager.DBA_GROUP);
} else {
permissions.setOwner(secman.getUser(uid));
permissions.setGroup(secman.getGroup(gid).getName());
}
permissions.setPermissions(perm);
created = istream.readLong();
DocumentImpl doc;
byte resourceType;
try {
while (istream.available() > 0) {
resourceType = istream.readByte();
switch (resourceType) {
case DocumentImpl.XML_FILE :
doc = new DocumentImpl(broker, this);
break;
case DocumentImpl.BINARY_FILE :
doc = new BinaryDocument(broker, this);
break;
case -1 :
return; // EOF found
default :
LOG.warn("unknown resource type: " + resourceType);
throw new IOException(
"unable to determine resource type while reading collection "
+ getName());
}
doc.read(istream);
addDocument(broker, doc);
}
} catch (EOFException e) {
}
}
/**
* Remove the specified sub-collection.
*
*@param name Description of the Parameter
*/
public void removeCollection(String name) throws LockException {
try {
lock.acquire(Lock.WRITE_LOCK);
subcollections.remove(name);
} finally {
lock.release();
}
}
/**
* Remove the specified document from the collection.
*
*@param name
*/
public void removeDocument(DBBroker broker, String docname)
throws PermissionDeniedException, TriggerException, LockException {
try {
lock.acquire(Lock.READ_LOCK);
Trigger trigger = null;
if (!docname.equals(COLLECTION_CONFIG_FILE)) {
if (triggersEnabled) {
CollectionConfiguration config = getConfiguration(broker);
if (config != null)
trigger = config
.getTrigger(Trigger.REMOVE_DOCUMENT_EVENT);
}
} else
configuration = null;
DocumentImpl doc = getDocument(broker, docname);
if (doc == null)
return;
if(doc.isLockedForWrite())
throw new PermissionDeniedException("Document " + doc.getFileName() +
" is locked for write");
if (!getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException(
"Write access to collection denied; user=" + broker.getUser().getName());
if (!doc.getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException("Permission to remove document denied");
if (trigger != null && triggersEnabled) {
trigger.prepare(Trigger.REMOVE_DOCUMENT_EVENT, broker, docname,
doc);
}
broker.removeDocument(getName() + '/' + docname);
documents.remove(docname);
broker.saveCollection(this);
} finally {
lock.release();
}
}
public void removeBinaryResource(DBBroker broker,
String docname) throws PermissionDeniedException, LockException {
try {
lock.acquire(Lock.WRITE_LOCK);
DocumentImpl doc = getDocument(broker, docname);
if(doc.isLockedForWrite())
throw new PermissionDeniedException("Document " + doc.getFileName() +
" is locked for write");
if (!getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException(
"write access to collection denied; user=" + broker.getUser().getName());
if (!doc.getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException("permission to remove document denied");
removeBinaryResource(broker, doc);
} finally {
lock.release();
}
}
public void removeBinaryResource(DBBroker broker,
DocumentImpl doc) throws PermissionDeniedException, LockException {
if (doc == null)
return;
if (doc.getResourceType() != DocumentImpl.BINARY_FILE)
throw new PermissionDeniedException("document " + doc.getFileName()
+ " is not a binary object");
if(doc.isLockedForWrite())
throw new PermissionDeniedException("Document " + doc.getFileName() +
" is locked for write");
if (!getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException(
"write access to collection denied; user=" + broker.getUser().getName());
if (!doc.getPermissions().validate(broker.getUser(), Permission.WRITE))
throw new PermissionDeniedException("permission to remove document denied");
try {
lock.acquire(Lock.WRITE_LOCK);
broker.removeBinaryResource((BinaryDocument) doc);
documents.remove(doc.getFileName());
broker.saveCollection(this);
} finally {
lock.release();
}
}
public DocumentImpl addDocument(DBBroker broker, String name, String data)
throws EXistException, PermissionDeniedException, TriggerException,
SAXException, LockException {
return addDocument(broker, name, data, false);
}
public DocumentImpl addDocument(DBBroker broker, String name, String data,
boolean privileged) throws EXistException,
PermissionDeniedException, TriggerException, SAXException,
LockException {
if (broker.isReadOnly())
throw new PermissionDeniedException("Database is read-only");
DocumentImpl document, oldDoc = null;
XMLReader reader;
InputSource source;
try {
lock.acquire(Lock.WRITE_LOCK);
if (hasDocument(name) && (oldDoc = getDocument(broker, name)) != null) {
if(oldDoc.isLockedForWrite())
throw new PermissionDeniedException("Document " + name +
" is locked for write");
// check if the document is locked by another user
User lockUser = oldDoc.getUserLock();
if(lockUser != null && !lockUser.equals(broker.getUser()))
throw new PermissionDeniedException("The document is locked by user " +
lockUser.getName());
// check if the document is currently being changed by someone else
Lock oldLock = oldDoc.getUpdateLock();
oldLock.acquire(Lock.WRITE_LOCK);
// do we have permissions for update?
if (!oldDoc.getPermissions().validate(broker.getUser(),
Permission.UPDATE))
throw new PermissionDeniedException(
"Document \""+name+"\" exists and update is not allowed");
if (!(getPermissions().validate(broker.getUser(), Permission.UPDATE) ||
getPermissions().validate(broker.getUser(), Permission.WRITE)))
throw new PermissionDeniedException(
"Document exists and update is not allowed for the collection");
// do we have write permissions?
} else if (!getPermissions().validate(broker.getUser(),
Permission.WRITE))
throw new PermissionDeniedException(
"Not allowed to write to collection " + getName());
document = new DocumentImpl(broker, name, this);
manageDocumentInformation(broker, name, oldDoc, document );
// setup triggers
Trigger trigger = null;
if (triggersEnabled && !name.equals(COLLECTION_CONFIG_FILE)) {
if (triggersEnabled) {
CollectionConfiguration config = getConfiguration(broker);
if (config != null) {
if (oldDoc == null)
trigger = config
.getTrigger(Trigger.STORE_DOCUMENT_EVENT);
else
trigger = config
.getTrigger(Trigger.UPDATE_DOCUMENT_EVENT);
}
}
} else
// set configuration to null if we are updating collection.xconf
configuration = null;
Indexer indexer = new Indexer(broker);
indexer.setDocument(document);
// add observers to the indexer
Observer observer;
broker.deleteObservers();
if (observers != null) {
for (Iterator i = observers.iterator(); i.hasNext(); ) {
observer = (Observer) i.next();
indexer.addObserver(observer);
broker.addObserver(observer);
}
}
// prepare the SAX parser
indexer.setValidating(true);
reader = getReader(broker);
reader.setEntityResolver(this);
if (trigger != null && triggersEnabled) {
reader.setContentHandler(trigger.getInputHandler());
reader.setProperty(
"http://xml.org/sax/properties/lexical-handler",
trigger.getLexicalInputHandler());
trigger.setOutputHandler(indexer);
trigger.setValidating(true);
// prepare the trigger
trigger.prepare(oldDoc == null
? Trigger.STORE_DOCUMENT_EVENT
: Trigger.UPDATE_DOCUMENT_EVENT, broker, name, oldDoc);
} else {
reader.setContentHandler(indexer);
reader
.setProperty(
"http://xml.org/sax/properties/lexical-handler",
indexer);
}
reader.setErrorHandler(indexer);
// first pass: parse the document to determine tree structure
LOG.debug("validating document " + name);
source = new InputSource(new StringReader(data));
try {
reader.parse(source);
} catch (IOException e) {
throw new EXistException(e);
}
document.setMaxDepth(document.getMaxDepth() + 1);
document.calculateTreeLevelStartPoints();
// new document is valid: remove old document
if (oldDoc != null) {
LOG.debug("removing old document " + oldDoc.getFileName());
if (oldDoc.getResourceType() == DocumentImpl.BINARY_FILE)
broker.removeBinaryResource((BinaryDocument) oldDoc);
else
broker.removeDocument(getName() + '/' + oldDoc.getFileName(), false);
// we continue to use the old document object and just replace its contents
oldDoc.copyOf(document);
indexer.setDocumentObject(oldDoc);
document = oldDoc;
} else {
document.getUpdateLock().acquire(Lock.WRITE_LOCK);
document.setDocId(broker.getNextDocId(this));
}
indexer.setValidating(false);
if (trigger != null)
trigger.setValidating(false);
} catch(EXistException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(SAXException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(PermissionDeniedException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(TriggerException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} finally {
lock.release();
}
// reset the input source
source = new InputSource(new StringReader(data));
// second pass: store the document
LOG.debug("storing document " + document.getDocId() + " ...");
try {
try {
reader.parse(source);
} catch (IOException e) {
throw new EXistException(e);
}
if(oldDoc == null)
addDocument(broker, document);
// broker.checkTree(document);
broker.addDocument(this, document);
broker.closeDocument();
broker.flush();
LOG.debug("document stored.");
// if we are running in privileged mode (e.g. backup/restore)
// notify the SecurityManager about changes
if (getName().equals(SecurityManager.SYSTEM) && document.getFileName().equals(SecurityManager.ACL_FILE)
&& privileged == false) {
// inform the security manager that system data has changed
LOG.debug("users.xml changed");
broker.getBrokerPool().reloadSecurityManager(broker);
}
} finally {
document.getUpdateLock().release(Lock.WRITE_LOCK);
}
broker.deleteObservers();
return document;
}
/** If an old document exists, keep information about the document
* @param broker
* @param name
* @param oldDoc
* @param document
*/
private void manageDocumentInformation(DBBroker broker, String name, DocumentImpl oldDoc,
DocumentImpl document ) {
if (oldDoc != null) {
document.setCreated(oldDoc.getCreated());
document.setLastModified(System.currentTimeMillis());
document.setPermissions(oldDoc.getPermissions());
} else {
document.setCreated(System.currentTimeMillis());
document.getPermissions().setOwner(broker.getUser());
document.getPermissions().setGroup(
broker.getUser().getPrimaryGroup());
}
}
public DocumentImpl addDocument(DBBroker broker, String name,
InputSource source) throws EXistException, LockException,
PermissionDeniedException, TriggerException, SAXException {
return addDocument(broker, name, source, false);
}
public DocumentImpl addDocument(DBBroker broker, String name,
InputSource source, boolean privileged) throws EXistException,
PermissionDeniedException, SAXException, TriggerException,
LockException {
if (broker.isReadOnly())
throw new PermissionDeniedException("Database is read-only");
DocumentImpl document = null, oldDoc = null;
XMLReader reader;
try {
lock.acquire(Lock.WRITE_LOCK);
if (hasDocument(name) && (oldDoc = getDocument(broker, name)) != null) {
// check if the document is locked by another user
User lockUser = oldDoc.getUserLock();
if(lockUser != null && !lockUser.equals(broker.getUser()))
throw new PermissionDeniedException("The document is locked by user " +
lockUser.getName());
// check if the document is currently being changed by someone else
Lock oldLock = oldDoc.getUpdateLock();
oldLock.acquire(Lock.WRITE_LOCK);
// do we have permissions for update?
if (!oldDoc.getPermissions().validate(broker.getUser(),
Permission.UPDATE))
throw new PermissionDeniedException(
"Document exists and update is not allowed");
if (!(getPermissions().validate(broker.getUser(), Permission.UPDATE) ||
getPermissions().validate(broker.getUser(), Permission.WRITE)))
throw new PermissionDeniedException(
"Document exists and update is not allowed for the collection");
// do we have write permissions?
} else if (!getPermissions().validate(broker.getUser(),
Permission.WRITE))
throw new PermissionDeniedException(
"Not allowed to write to collection " + getName());
document = new DocumentImpl(broker, name, this);
manageDocumentInformation(broker, name, oldDoc, document );
// setup triggers
Trigger trigger = null;
if (triggersEnabled && !name.equals(COLLECTION_CONFIG_FILE)) {
if (triggersEnabled) {
CollectionConfiguration config = getConfiguration(broker);
if (config != null) {
if (oldDoc == null)
trigger = config
.getTrigger(Trigger.STORE_DOCUMENT_EVENT);
else
trigger = config
.getTrigger(Trigger.UPDATE_DOCUMENT_EVENT);
}
}
} else
// set configuration to null if we are updating collection.xconf
configuration = null;
Indexer parser = new Indexer(broker);
parser.setDocument(document);
// add observers to the indexer
Observer observer;
broker.deleteObservers();
if (observers != null) {
for (Iterator i = observers.iterator(); i.hasNext(); ) {
observer = (Observer) i.next();
parser.addObserver(observer);
broker.addObserver(observer);
}
}
// prepare the SAX parser
parser.setValidating(true);
reader = getReader(broker);
reader.setEntityResolver(this);
if (trigger != null && triggersEnabled) {
reader.setContentHandler(trigger.getInputHandler());
reader.setProperty(
"http://xml.org/sax/properties/lexical-handler",
trigger.getLexicalInputHandler());
trigger.setOutputHandler(parser);
trigger.setLexicalOutputHandler(parser);
trigger.setValidating(true);
// prepare the trigger
trigger.prepare(oldDoc == null
? Trigger.STORE_DOCUMENT_EVENT
: Trigger.UPDATE_DOCUMENT_EVENT, broker, name, oldDoc);
} else {
reader.setContentHandler(parser);
reader
.setProperty(
"http://xml.org/sax/properties/lexical-handler",
parser);
}
reader.setErrorHandler(parser);
// first pass: parse the document to determine tree structure
LOG.debug("validating document " + name);
try {
reader.parse(source);
} catch (IOException e) {
throw new EXistException(e);
}
document.setMaxDepth(document.getMaxDepth() + 1);
document.calculateTreeLevelStartPoints();
// new document is valid: remove old document
if (oldDoc != null) {
LOG.debug("removing old document " + oldDoc.getFileName());
if (oldDoc.getResourceType() == DocumentImpl.BINARY_FILE)
broker.removeBinaryResource((BinaryDocument) oldDoc);
else
broker.removeDocument(getName() + '/' + oldDoc.getFileName(), false);
oldDoc.copyOf(document);
parser.setDocumentObject(oldDoc);
document = oldDoc;
} else {
document.getUpdateLock().acquire(Lock.WRITE_LOCK);
document.setDocId(broker.getNextDocId(this));
}
parser.setValidating(false);
if (trigger != null)
trigger.setValidating(false);
} catch(EXistException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(SAXException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(PermissionDeniedException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(TriggerException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} finally {
lock.release();
}
// reset the input source
try {
final InputStream is = source.getByteStream();
if (is != null)
is.reset();
else {
final Reader cs = source.getCharacterStream();
if (cs != null)
cs.reset();
}
} catch (IOException e) {
LOG.debug("could not reset input source", e);
}
// second pass: store the document
LOG.debug("storing document ...");
try {
try {
reader.parse(source);
} catch (IOException e) {
throw new EXistException(e);
}
if(oldDoc == null)
addDocument(broker, document);
broker.addDocument(this, document);
broker.closeDocument();
broker.flush();
// if we are running in privileged mode (e.g. backup/restore)
// notify the SecurityManager about changes
if (getName().equals(SecurityManager.SYSTEM) && document.getFileName().equals(SecurityManager.ACL_FILE)
&& privileged == false) {
// inform the security manager that system data has changed
LOG.debug("users.xml changed");
broker.getBrokerPool().reloadSecurityManager(broker);
}
} finally {
document.getUpdateLock().release(Lock.WRITE_LOCK);
}
broker.deleteObservers();
return document;
}
public DocumentImpl addDocument(DBBroker broker, String name, Node node)
throws EXistException, PermissionDeniedException, TriggerException,
SAXException, LockException {
return addDocument(broker, name, node, false);
}
public DocumentImpl addDocument(DBBroker broker, String name, Node node,
boolean privileged) throws EXistException, LockException,
PermissionDeniedException, TriggerException, SAXException {
Indexer parser = new Indexer(broker);
if (broker.isReadOnly())
throw new PermissionDeniedException("Database is read-only");
DocumentImpl document, oldDoc = null;
DOMStreamer streamer;
try {
lock.acquire(Lock.WRITE_LOCK);
if (hasDocument(name) && (oldDoc = getDocument(broker, name)) != null) {
// check if the document is locked by another user
User lockUser = oldDoc.getUserLock();
if(lockUser != null && !lockUser.equals(broker.getUser()))
throw new PermissionDeniedException("The document is locked by user " +
lockUser.getName());
// check if the document is currently being changed by someone else
oldDoc.getUpdateLock().acquire(Lock.WRITE_LOCK);
// do we have permissions for update?
if (!oldDoc.getPermissions().validate(broker.getUser(),
Permission.UPDATE))
throw new PermissionDeniedException(
"document exists and update " + "is not allowed");
if (!(getPermissions().validate(broker.getUser(), Permission.UPDATE) ||
getPermissions().validate(broker.getUser(), Permission.WRITE)))
throw new PermissionDeniedException(
"Document exists and update is not allowed for the collection");
// no: do we have write permissions?
} else if (!getPermissions().validate(broker.getUser(),
Permission.WRITE))
throw new PermissionDeniedException(
"not allowed to write to collection " + getName());
document = new DocumentImpl(broker, name, this);
manageDocumentInformation(broker, name, oldDoc, document );
// setup triggers
Trigger trigger = null;
if (triggersEnabled && !name.equals(COLLECTION_CONFIG_FILE)) {
if (triggersEnabled) {
CollectionConfiguration config = getConfiguration(broker);
if (config != null) {
if (oldDoc == null)
trigger = config
.getTrigger(Trigger.STORE_DOCUMENT_EVENT);
else
trigger = config
.getTrigger(Trigger.UPDATE_DOCUMENT_EVENT);
}
}
} else
// set configuration to null if we are updating collection.xconf
configuration = null;
parser.setDocument(document);
// add observers to the indexer
Observer observer;
broker.deleteObservers();
if (observers != null) {
for (Iterator i = observers.iterator(); i.hasNext(); ) {
observer = (Observer) i.next();
parser.addObserver(observer);
broker.addObserver(observer);
}
}
parser.setValidating(true);
streamer = new DOMStreamer();
if (trigger != null && triggersEnabled) {
streamer.setContentHandler(trigger.getInputHandler());
streamer.setLexicalHandler(trigger.getLexicalInputHandler());
trigger.setOutputHandler(parser);
trigger.setValidating(true);
// prepare the trigger
trigger.prepare(oldDoc == null
? Trigger.STORE_DOCUMENT_EVENT
: Trigger.UPDATE_DOCUMENT_EVENT, broker, name, oldDoc);
} else {
streamer.setContentHandler(parser);
streamer.setLexicalHandler(parser);
}
// first pass: parse the document to determine tree structure
LOG.debug("validating document " + name);
streamer.serialize(node, true);
document.setMaxDepth(document.getMaxDepth() + 1);
document.calculateTreeLevelStartPoints();
// new document is valid: remove old document
if (oldDoc != null) {
LOG.debug("removing old document " + oldDoc.getFileName());
if (oldDoc.getResourceType() == DocumentImpl.BINARY_FILE)
broker.removeBinaryResource((BinaryDocument) oldDoc);
else
broker.removeDocument(getName() + '/' + oldDoc.getFileName(), false);
oldDoc.copyOf(document);
parser.setDocumentObject(oldDoc);
document = oldDoc;
} else {
document.getUpdateLock().acquire(Lock.WRITE_LOCK);
document.setDocId(broker.getNextDocId(this));
}
parser.setValidating(false);
if (trigger != null)
trigger.setValidating(false);
} catch(EXistException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(SAXException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(PermissionDeniedException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} catch(TriggerException e) {
if(oldDoc != null) oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
throw e;
} finally {
lock.release();
}
try {
// second pass: store the document
if(LOG.isDebugEnabled())
LOG.debug("storing document " + document.getFileName());
streamer.serialize(node, true);
if(oldDoc == null)
addDocument(broker, document);
broker.addDocument(this, document);
broker.closeDocument();
broker.flush();
// if we are running in privileged mode (e.g. backup/restore)
// notify the SecurityManager about changes
if (getName().equals(SecurityManager.SYSTEM) && document.getFileName().equals(SecurityManager.ACL_FILE)
&& privileged == false) {
// inform the security manager that system data has changed
if(LOG.isDebugEnabled())
LOG.debug("users.xml changed");
broker.getBrokerPool().reloadSecurityManager(broker);
}
} finally {
document.getUpdateLock().release(Lock.WRITE_LOCK);
}
broker.deleteObservers();
return document;
}
public BinaryDocument addBinaryResource(DBBroker broker,
String name, byte[] data) throws EXistException,
PermissionDeniedException, LockException {
if (broker.isReadOnly())
throw new PermissionDeniedException("Database is read-only");
BinaryDocument blob = null;
try {
lock.acquire(Lock.WRITE_LOCK);
DocumentImpl oldDoc = getDocument(broker, name);
if (oldDoc != null) {
if(oldDoc.isLockedForWrite())
throw new PermissionDeniedException("Document " + name +
" is already locked for write");
// check if the document is locked by another user
User lockUser = oldDoc.getUserLock();
if(lockUser != null && !lockUser.equals(broker.getUser()))
throw new PermissionDeniedException("The document is locked by user " +
lockUser.getName());
// do we have permissions for update?
if (!oldDoc.getPermissions().validate(broker.getUser(),
Permission.UPDATE))
throw new PermissionDeniedException(
"document exists and update is not allowed");
// no: do we have write permissions?
} else if (!getPermissions().validate(broker.getUser(),
Permission.WRITE))
throw new PermissionDeniedException(
"not allowed to write to collection " + getName());
blob = new BinaryDocument(broker, name, this);
// if (oldDoc != null) {
// blob.setCreated(oldDoc.getCreated());
// blob.setLastModified(System.currentTimeMillis());
// blob.setPermissions(oldDoc.getPermissions());
//
// LOG.debug("removing old document " + oldDoc.getFileName());
// if (oldDoc instanceof BinaryDocument)
// broker.removeBinaryResource((BinaryDocument) oldDoc);
// else
// broker.removeDocument(getName() + '/' + oldDoc.getFileName());
// } else {
// blob.setCreated(System.currentTimeMillis());
// blob.getPermissions().setOwner(broker.getUser());
// blob.getPermissions().setGroup(
// broker.getUser().getPrimaryGroup());
// }
manageDocumentInformation(broker, name, oldDoc, blob );
if (oldDoc != null) {
LOG.debug("removing old document " + oldDoc.getFileName());
if (oldDoc instanceof BinaryDocument)
broker.removeBinaryResource((BinaryDocument) oldDoc);
else
broker.removeDocument(getName() + '/' + oldDoc.getFileName());
}
broker.storeBinaryResource(blob, data);
addDocument(broker, blob);
broker.addDocument(this, blob);
broker.closeDocument();
return blob;
} finally {
lock.release();
}
}
public void setId(short id) {
this.collectionId = id;
}
public void setPermissions(int mode) throws LockException {
try {
lock.acquire(Lock.WRITE_LOCK);
permissions.setPermissions(mode);
} finally {
lock.release();
}
}
public void setPermissions(String mode) throws SyntaxException, LockException {
try {
lock.acquire(Lock.WRITE_LOCK);
permissions.setPermissions(mode);
} finally {
lock.release();
}
}
/**
* Set permissions for the collection.
*
* @param permissions
*/
public void setPermissions(Permission permissions) throws LockException {
try {
lock.acquire(Lock.WRITE_LOCK);
this.permissions = permissions;
} finally {
lock.release();
}
}
/**
* Write collection contents to stream.
*
* @param ostream
* @throws IOException
*/
public void write(DBBroker broker, VariableByteOutputStream ostream)
throws IOException {
ostream.writeShort(collectionId);
ostream.writeInt(subcollections.size());
String childColl;
for (Iterator i = subcollections.iterator(); i.hasNext(); ) {
childColl = (String) i.next();
ostream.writeUTF(childColl);
}
org.exist.security.SecurityManager secman = broker.getBrokerPool()
.getSecurityManager();
if (secman == null) {
ostream.writeInt(1);
ostream.writeInt(1);
} else {
User user = secman.getUser(permissions.getOwner());
Group group = secman.getGroup(permissions.getOwnerGroup());
ostream.writeInt(user.getUID());
ostream.writeInt(group.getId());
}
ostream.writeByte((byte) permissions.getPermissions());
ostream.writeLong(created);
if(reloadRequired) {
broker.reloadCollection(this);
reloadRequired = false;
}
DocumentImpl doc;
for (Iterator i = documents.values().iterator(); i.hasNext(); ) {
doc = (DocumentImpl) i.next();
doc.write(ostream);
}
}
private CollectionConfiguration getConfiguration(DBBroker broker) {
if (configuration == null)
configuration = readCollectionConfiguration(broker);
return configuration;
}
private CollectionConfiguration readCollectionConfiguration(DBBroker broker) {
if (hasDocument(COLLECTION_CONFIG_FILE)) {
DocumentImpl doc = getDocument(broker, COLLECTION_CONFIG_FILE);
if(doc == null) {
LOG.warn("collection.xconf exists but could not be loaded");
return null;
}
LOG.debug("found collection.xconf");
triggersEnabled = false;
try {
return new CollectionConfiguration(broker, this, doc);
} catch (CollectionConfigurationException e) {
LOG.warn("Failed to load collection configuration " + e.getMessage());
} finally {
triggersEnabled = true;
}
}
return null;
}
/**
* Set the internal storage address of the collection data.
*
* @param addr
*/
public void setAddress(long addr) {
this.address = addr;
}
public long getAddress() {
return this.address;
}
public void setCreationTime(long ms) {
created = ms;
}
public long getCreationTime() {
return created;
}
public void setTriggersEnabled(boolean enabled) {
try {
lock.acquire(Lock.WRITE_LOCK);
this.triggersEnabled = enabled;
} catch (LockException e) {
LOG.warn(e.getMessage(), e);
this.triggersEnabled = enabled;
} finally {
lock.release();
}
}
private XMLReader getReader(DBBroker broker) throws EXistException,
SAXException {
Configuration config = broker.getConfiguration();
// get validation settings
String option = (String) config.getProperty("indexer.validation");
if (option != null) {
if (option.equals("true"))
validation = VALIDATION_ENABLED;
else if (option.equals("auto"))
validation = VALIDATION_AUTO;
else
validation = VALIDATION_DISABLED;
}
resolver = (CatalogResolver) config.getProperty("resolver");
// create a SAX parser
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
if (validation == VALIDATION_AUTO || validation == VALIDATION_ENABLED)
saxFactory.setValidating(true);
else
saxFactory.setValidating(false);
saxFactory.setNamespaceAware(true);
try {
setFeature(saxFactory,
"http://xml.org/sax/features/namespace-prefixes", true);
setFeature(saxFactory,
"http://apache.org/xml/features/validation/dynamic",
validation == VALIDATION_AUTO);
setFeature(saxFactory,
"http://apache.org/xml/features/validation/schema",
validation == VALIDATION_AUTO
|| validation == VALIDATION_ENABLED);
SAXParser sax = saxFactory.newSAXParser();
XMLReader parser = sax.getXMLReader();
return parser;
} catch (ParserConfigurationException e) {
LOG.warn(e);
throw new EXistException(e);
}
}
/**
* Try to resolve external entities.
*
* This method forwards the request to the resolver. If that fails,
* the method replaces absolute file names with relative ones
* and retries to resolve. This makes it possible to use relative
* file names in the catalog.
*
* @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
*/
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
InputSource is = resolver.resolveEntity(publicId, systemId);
// if resolution failed and publicId == null,
// try to make absolute file names relative and retry
if (is == null) {
if (publicId != null)
return null;
URL url = new URL(systemId);
if (url.getProtocol().equals("file")) {
String path = url.getPath();
File f = new File(path);
if (!f.canRead())
return resolver.resolveEntity(null, f.getName());
else
return new InputSource(f.getAbsolutePath());
} else
return new InputSource(url.openStream());
}
return is;
}
private void setFeature(SAXParserFactory factory, String feature,
boolean value) {
try {
factory.setFeature(feature, value);
} catch (SAXNotRecognizedException e) {
LOG.warn(e);
} catch (SAXNotSupportedException snse) {
LOG.warn(snse);
} catch (ParserConfigurationException pce) {
LOG.warn(pce);
}
}
/* (non-Javadoc)
* @see java.util.Observable#addObserver(java.util.Observer)
*/
public void addObserver(Observer o) {
if (observers == null)
observers = new ArrayList(1);
if (!observers.contains(o))
observers.add(o);
}
/* (non-Javadoc)
* @see java.util.Observable#deleteObservers()
*/
public void deleteObservers() {
if (observers != null)
observers.clear();
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#getKey()
*/
public long getKey() {
return collectionId;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#getReferenceCount()
*/
public int getReferenceCount() {
return refCount;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#incReferenceCount()
*/
public int incReferenceCount() {
return ++refCount;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#decReferenceCount()
*/
public int decReferenceCount() {
return refCount > 0 ? --refCount : 0;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#setReferenceCount(int)
*/
public void setReferenceCount(int count) {
refCount = count;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#setTimestamp(int)
*/
public void setTimestamp(int timestamp) {
this.timestamp = timestamp;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#getTimestamp()
*/
public int getTimestamp() {
return timestamp;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#release()
*/
public boolean sync() {
return false;
}
/* (non-Javadoc)
* @see org.exist.storage.cache.Cacheable#isDirty()
*/
public boolean isDirty() {
return false;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("[");
for(Iterator i = documents.keySet().iterator(); i.hasNext(); ) {
buf.append(i.next());
if(i.hasNext())
buf.append(", ");
}
buf.append("]");
return buf.toString();
}
}
| Refactoring: extract method:
checkPermissions(DBBroker broker, String name)
svn path=/trunk/eXist-1.0/; revision=431
| src/org/exist/collections/Collection.java | Refactoring: extract method: checkPermissions(DBBroker broker, String name) | <ide><path>rc/org/exist/collections/Collection.java
<ide> XMLReader reader;
<ide> InputSource source;
<ide> try {
<del> lock.acquire(Lock.WRITE_LOCK);
<del> if (hasDocument(name) && (oldDoc = getDocument(broker, name)) != null) {
<del> if(oldDoc.isLockedForWrite())
<del> throw new PermissionDeniedException("Document " + name +
<del> " is locked for write");
<del> // check if the document is locked by another user
<del> User lockUser = oldDoc.getUserLock();
<del> if(lockUser != null && !lockUser.equals(broker.getUser()))
<del> throw new PermissionDeniedException("The document is locked by user " +
<del> lockUser.getName());
<del>
<del> // check if the document is currently being changed by someone else
<del> Lock oldLock = oldDoc.getUpdateLock();
<del> oldLock.acquire(Lock.WRITE_LOCK);
<del>
<del> // do we have permissions for update?
<del> if (!oldDoc.getPermissions().validate(broker.getUser(),
<del> Permission.UPDATE))
<del> throw new PermissionDeniedException(
<del> "Document \""+name+"\" exists and update is not allowed");
<del> if (!(getPermissions().validate(broker.getUser(), Permission.UPDATE) ||
<del> getPermissions().validate(broker.getUser(), Permission.WRITE)))
<del> throw new PermissionDeniedException(
<del> "Document exists and update is not allowed for the collection");
<del> // do we have write permissions?
<del> } else if (!getPermissions().validate(broker.getUser(),
<del> Permission.WRITE))
<del> throw new PermissionDeniedException(
<del> "Not allowed to write to collection " + getName());
<add> oldDoc = checkPermissions(broker, name);
<ide>
<ide> document = new DocumentImpl(broker, name, this);
<ide> manageDocumentInformation(broker, name, oldDoc, document );
<ide> return document;
<ide> }
<ide>
<del> /** If an old document exists, keep information about the document
<add> /** If an old document exists, keep information about the document.
<ide> * @param broker
<ide> * @param name
<ide> * @param oldDoc
<ide> }
<ide> }
<ide>
<add> /** Check Permissions about user and document, and throw exceptions if necessary.
<add> * @param broker
<add> * @param name
<add> * @return
<add> * @throws LockException
<add> * @throws PermissionDeniedException
<add> */
<add> private DocumentImpl checkPermissions(DBBroker broker, String name) throws LockException, PermissionDeniedException {
<add> DocumentImpl oldDoc = null;
<add> lock.acquire(Lock.WRITE_LOCK);
<add> if (hasDocument(name) && (oldDoc = getDocument(broker, name)) != null) {
<add>
<add> // jmv: Note: this was only in addDocument(DBBroker broker, String name, String data,)
<add> if(oldDoc.isLockedForWrite())
<add> throw new PermissionDeniedException("Document " + name +
<add> " is locked for write");
<add>
<add> // check if the document is locked by another user
<add> User lockUser = oldDoc.getUserLock();
<add> if(lockUser != null && !lockUser.equals(broker.getUser()))
<add> throw new PermissionDeniedException("The document is locked by user " +
<add> lockUser.getName());
<add>
<add> // check if the document is currently being changed by someone else
<add> Lock oldLock = oldDoc.getUpdateLock();
<add> oldLock.acquire(Lock.WRITE_LOCK);
<add>
<add> // do we have permissions for update?
<add> if (!oldDoc.getPermissions().validate(broker.getUser(),
<add> Permission.UPDATE))
<add> throw new PermissionDeniedException(
<add> "Document exists and update is not allowed");
<add> if (!(getPermissions().validate(broker.getUser(), Permission.UPDATE) ||
<add> getPermissions().validate(broker.getUser(), Permission.WRITE)))
<add> throw new PermissionDeniedException(
<add> "Document exists and update is not allowed for the collection");
<add> // do we have write permissions?
<add> } else if (!getPermissions().validate(broker.getUser(),
<add> Permission.WRITE))
<add> throw new PermissionDeniedException(
<add> "Not allowed to write to collection " + getName());
<add> return oldDoc;
<add> }
<add>
<ide> public DocumentImpl addDocument(DBBroker broker, String name,
<ide> InputSource source) throws EXistException, LockException,
<ide> PermissionDeniedException, TriggerException, SAXException {
<ide> DocumentImpl document = null, oldDoc = null;
<ide> XMLReader reader;
<ide> try {
<del> lock.acquire(Lock.WRITE_LOCK);
<del> if (hasDocument(name) && (oldDoc = getDocument(broker, name)) != null) {
<del> // check if the document is locked by another user
<del> User lockUser = oldDoc.getUserLock();
<del> if(lockUser != null && !lockUser.equals(broker.getUser()))
<del> throw new PermissionDeniedException("The document is locked by user " +
<del> lockUser.getName());
<del>
<del> // check if the document is currently being changed by someone else
<del> Lock oldLock = oldDoc.getUpdateLock();
<del> oldLock.acquire(Lock.WRITE_LOCK);
<del>
<del> // do we have permissions for update?
<del> if (!oldDoc.getPermissions().validate(broker.getUser(),
<del> Permission.UPDATE))
<del> throw new PermissionDeniedException(
<del> "Document exists and update is not allowed");
<del> if (!(getPermissions().validate(broker.getUser(), Permission.UPDATE) ||
<del> getPermissions().validate(broker.getUser(), Permission.WRITE)))
<del> throw new PermissionDeniedException(
<del> "Document exists and update is not allowed for the collection");
<del> // do we have write permissions?
<del> } else if (!getPermissions().validate(broker.getUser(),
<del> Permission.WRITE))
<del> throw new PermissionDeniedException(
<del> "Not allowed to write to collection " + getName());
<add> oldDoc = checkPermissions(broker, name);
<ide>
<ide> document = new DocumentImpl(broker, name, this);
<ide> manageDocumentInformation(broker, name, oldDoc, document );
<ide> } catch (IOException e) {
<ide> throw new EXistException(e);
<ide> }
<del> document.setMaxDepth(document.getMaxDepth() + 1);
<add> document.setMaxDepth(document.getMaxDepth() + 1);//ddddddddddddddddddddddddddddddd
<ide> document.calculateTreeLevelStartPoints();
<ide> // new document is valid: remove old document
<ide> if (oldDoc != null) {
<ide> DocumentImpl document, oldDoc = null;
<ide> DOMStreamer streamer;
<ide> try {
<del> lock.acquire(Lock.WRITE_LOCK);
<del> if (hasDocument(name) && (oldDoc = getDocument(broker, name)) != null) {
<del> // check if the document is locked by another user
<del> User lockUser = oldDoc.getUserLock();
<del> if(lockUser != null && !lockUser.equals(broker.getUser()))
<del> throw new PermissionDeniedException("The document is locked by user " +
<del> lockUser.getName());
<del>
<del> // check if the document is currently being changed by someone else
<del> oldDoc.getUpdateLock().acquire(Lock.WRITE_LOCK);
<del>
<del> // do we have permissions for update?
<del> if (!oldDoc.getPermissions().validate(broker.getUser(),
<del> Permission.UPDATE))
<del> throw new PermissionDeniedException(
<del> "document exists and update " + "is not allowed");
<del> if (!(getPermissions().validate(broker.getUser(), Permission.UPDATE) ||
<del> getPermissions().validate(broker.getUser(), Permission.WRITE)))
<del> throw new PermissionDeniedException(
<del> "Document exists and update is not allowed for the collection");
<del> // no: do we have write permissions?
<del> } else if (!getPermissions().validate(broker.getUser(),
<del> Permission.WRITE))
<del> throw new PermissionDeniedException(
<del> "not allowed to write to collection " + getName());
<add>
<add> oldDoc = checkPermissions(broker, name);
<ide>
<ide> document = new DocumentImpl(broker, name, this);
<ide> manageDocumentInformation(broker, name, oldDoc, document );
<ide> throw new PermissionDeniedException("Database is read-only");
<ide> BinaryDocument blob = null;
<ide> try {
<del> lock.acquire(Lock.WRITE_LOCK);
<del> DocumentImpl oldDoc = getDocument(broker, name);
<del> if (oldDoc != null) {
<del> if(oldDoc.isLockedForWrite())
<del> throw new PermissionDeniedException("Document " + name +
<del> " is already locked for write");
<del> // check if the document is locked by another user
<del> User lockUser = oldDoc.getUserLock();
<del> if(lockUser != null && !lockUser.equals(broker.getUser()))
<del> throw new PermissionDeniedException("The document is locked by user " +
<del> lockUser.getName());
<del> // do we have permissions for update?
<del> if (!oldDoc.getPermissions().validate(broker.getUser(),
<del> Permission.UPDATE))
<del> throw new PermissionDeniedException(
<del> "document exists and update is not allowed");
<del> // no: do we have write permissions?
<del> } else if (!getPermissions().validate(broker.getUser(),
<del> Permission.WRITE))
<del> throw new PermissionDeniedException(
<del> "not allowed to write to collection " + getName());
<add>
<add> DocumentImpl oldDoc = checkPermissions(broker, name);
<ide>
<ide> blob = new BinaryDocument(broker, name, this);
<del>// if (oldDoc != null) {
<del>// blob.setCreated(oldDoc.getCreated());
<del>// blob.setLastModified(System.currentTimeMillis());
<del>// blob.setPermissions(oldDoc.getPermissions());
<del>//
<del>// LOG.debug("removing old document " + oldDoc.getFileName());
<del>// if (oldDoc instanceof BinaryDocument)
<del>// broker.removeBinaryResource((BinaryDocument) oldDoc);
<del>// else
<del>// broker.removeDocument(getName() + '/' + oldDoc.getFileName());
<del>// } else {
<del>// blob.setCreated(System.currentTimeMillis());
<del>// blob.getPermissions().setOwner(broker.getUser());
<del>// blob.getPermissions().setGroup(
<del>// broker.getUser().getPrimaryGroup());
<del>// }
<ide>
<ide> manageDocumentInformation(broker, name, oldDoc, blob );
<ide> |
|
Java | apache-2.0 | 03e7113f54598cc582ef662c4adb28d90791ba5b | 0 | xujeff/tianti,xujeff/tianti | package com.jeff.tianti.cms.dto;
import com.jeff.tianti.common.dto.CommonQueryDTO;
/**
* @author xujianfang
* @desc ArticleQueryDTO
* @date 2017-03-16
*/
public class ArticleQueryDTO extends CommonQueryDTO{
//数据获取类型(如全部、已审核等)
private String type;
//根栏目ID
private String rootColumnId;
//栏目ID(叶子节点)
private String columnId;
//标题
private String title;
//发布者
private String publisher;
//开始时间
private String startDate;
//结束时间
private String endDate;
//前N条数据
private Integer top;
//逻辑删除
private String deleteFlag;
//按发布日期排序样式:up为升序,down为降序
private String createDateSortCss;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRootColumnId() {
return rootColumnId;
}
public void setRootColumnId(String rootColumnId) {
this.rootColumnId = rootColumnId;
}
public String getColumnId() {
return columnId;
}
public void setColumnId(String columnId) {
this.columnId = columnId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(String deleteFlag) {
this.deleteFlag = deleteFlag;
}
public String getCreateDateSortCss() {
return createDateSortCss;
}
public void setCreateDateSortCss(String createDateSortCss) {
this.createDateSortCss = createDateSortCss;
}
public Integer getTop() {
return top;
}
public void setTop(Integer top) {
this.top = top;
}
} | tianti-cms/src/main/java/com/jeff/tianti/cms/dto/ArticleQueryDTO.java | package com.jeff.tianti.cms.dto;
import com.jeff.tianti.common.dto.CommonQueryDTO;
/**
* @author xujianfang
* @desc ArticleQueryDTO
* @date 2017-03-16
*/
public class ArticleQueryDTO extends CommonQueryDTO{
//数据获取类型(如全部、已审核等)
private String type;
//根栏目ID
private String rootColumnId;
//栏目ID(叶子节点)
private String columnId;
//标题
private String title;
//发布者
private String publisher;
//开始时间
private String startDate;
//结束时间
private String endDate;
//前N条数据
private Integer top;
//按发布日期排序样式:up为升序,down为降序
private String createDateSortCss;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRootColumnId() {
return rootColumnId;
}
public void setRootColumnId(String rootColumnId) {
this.rootColumnId = rootColumnId;
}
public String getColumnId() {
return columnId;
}
public void setColumnId(String columnId) {
this.columnId = columnId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getCreateDateSortCss() {
return createDateSortCss;
}
public void setCreateDateSortCss(String createDateSortCss) {
this.createDateSortCss = createDateSortCss;
}
public Integer getTop() {
return top;
}
public void setTop(Integer top) {
this.top = top;
}
} | 前端新增删除过滤
| tianti-cms/src/main/java/com/jeff/tianti/cms/dto/ArticleQueryDTO.java | 前端新增删除过滤 | <ide><path>ianti-cms/src/main/java/com/jeff/tianti/cms/dto/ArticleQueryDTO.java
<ide>
<ide> //前N条数据
<ide> private Integer top;
<add>
<add> //逻辑删除
<add> private String deleteFlag;
<ide>
<ide> //按发布日期排序样式:up为升序,down为降序
<ide> private String createDateSortCss;
<ide> this.endDate = endDate;
<ide> }
<ide>
<add> public String getDeleteFlag() {
<add> return deleteFlag;
<add> }
<add>
<add> public void setDeleteFlag(String deleteFlag) {
<add> this.deleteFlag = deleteFlag;
<add> }
<add>
<ide> public String getCreateDateSortCss() {
<ide> return createDateSortCss;
<ide> } |
|
Java | apache-2.0 | aa30f5fbabc99090f73ae4e0bd6fdf018e1b180e | 0 | ryano144/intellij-community,signed/intellij-community,supersven/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,ernestp/consulo,Lekanich/intellij-community,consulo/consulo,michaelgallacher/intellij-community,fitermay/intellij-community,allotria/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,samthor/intellij-community,izonder/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ibinti/intellij-community,robovm/robovm-studio,vladmm/intellij-community,diorcety/intellij-community,kool79/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,vladmm/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,slisson/intellij-community,dslomov/intellij-community,semonte/intellij-community,samthor/intellij-community,gnuhub/intellij-community,slisson/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,da1z/intellij-community,apixandru/intellij-community,adedayo/intellij-community,caot/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,slisson/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,ryano144/intellij-community,consulo/consulo,xfournet/intellij-community,semonte/intellij-community,petteyg/intellij-community,hurricup/intellij-community,blademainer/intellij-community,adedayo/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,consulo/consulo,adedayo/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,petteyg/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,hurricup/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,supersven/intellij-community,da1z/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,jagguli/intellij-community,asedunov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,vladmm/intellij-community,retomerz/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,da1z/intellij-community,robovm/robovm-studio,petteyg/intellij-community,wreckJ/intellij-community,kool79/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,allotria/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,kool79/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,izonder/intellij-community,holmes/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ernestp/consulo,apixandru/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,supersven/intellij-community,izonder/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,ibinti/intellij-community,slisson/intellij-community,supersven/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,fnouama/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,ernestp/consulo,youdonghai/intellij-community,robovm/robovm-studio,asedunov/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,petteyg/intellij-community,supersven/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,clumsy/intellij-community,clumsy/intellij-community,signed/intellij-community,caot/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,fnouama/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,holmes/intellij-community,slisson/intellij-community,diorcety/intellij-community,signed/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,caot/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,vladmm/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,tmpgit/intellij-community,izonder/intellij-community,da1z/intellij-community,dslomov/intellij-community,semonte/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,kool79/intellij-community,jagguli/intellij-community,da1z/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,semonte/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,semonte/intellij-community,FHannes/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,allotria/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,asedunov/intellij-community,caot/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,diorcety/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,izonder/intellij-community,semonte/intellij-community,fitermay/intellij-community,fnouama/intellij-community,hurricup/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,amith01994/intellij-community,xfournet/intellij-community,jagguli/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,holmes/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,samthor/intellij-community,holmes/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,ryano144/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,tmpgit/intellij-community,semonte/intellij-community,caot/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,caot/intellij-community,izonder/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,consulo/consulo,samthor/intellij-community,caot/intellij-community,FHannes/intellij-community,da1z/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,caot/intellij-community,da1z/intellij-community,holmes/intellij-community,samthor/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,samthor/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,supersven/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,consulo/consulo,retomerz/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,kdwink/intellij-community,FHannes/intellij-community,FHannes/intellij-community,signed/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,fitermay/intellij-community,signed/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,hurricup/intellij-community,slisson/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,da1z/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,allotria/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,signed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,semonte/intellij-community,diorcety/intellij-community,apixandru/intellij-community,ibinti/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,asedunov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,retomerz/intellij-community,samthor/intellij-community,ernestp/consulo,orekyuu/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,fitermay/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,apixandru/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,kool79/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,apixandru/intellij-community,kdwink/intellij-community,slisson/intellij-community,hurricup/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,signed/intellij-community,kool79/intellij-community,allotria/intellij-community,signed/intellij-community,clumsy/intellij-community,slisson/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,caot/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,supersven/intellij-community,slisson/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,diorcety/intellij-community,retomerz/intellij-community,holmes/intellij-community,holmes/intellij-community,xfournet/intellij-community,allotria/intellij-community,akosyakov/intellij-community,samthor/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,izonder/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,kool79/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,holmes/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,caot/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,clumsy/intellij-community,ernestp/consulo,apixandru/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,kool79/intellij-community,wreckJ/intellij-community,signed/intellij-community,consulo/consulo,ahb0327/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,ernestp/consulo,ftomassetti/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,diorcety/intellij-community,ibinti/intellij-community,xfournet/intellij-community | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.projectRoots.impl;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.ui.HtmlListCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import javax.swing.*;
/**
* @author yole
*/
public class SdkListCellRenderer extends HtmlListCellRenderer<Sdk> {
private String myNullText = "";
private boolean myShowHomePath;
public SdkListCellRenderer(final ListCellRenderer listCellRenderer) {
super(listCellRenderer);
}
public SdkListCellRenderer(final String nullText, final ListCellRenderer listCellRenderer) {
super(listCellRenderer);
myNullText = nullText;
}
public SdkListCellRenderer(final String nullText, final boolean showHomePath, final ListCellRenderer listCellRenderer) {
super(listCellRenderer);
myNullText = nullText;
myShowHomePath = showHomePath;
}
@Override
protected void doCustomize(final JList list, final Sdk sdk, final int index, final boolean selected, final boolean hasFocus) {
if (sdk != null) {
// icon
setIcon(getSdkIcon(sdk));
// text
append(sdk.getName());
if (myShowHomePath) {
append(" (" + FileUtil.toSystemDependentName(sdk.getHomePath()) + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES);
}
}
else {
append(myNullText);
}
}
protected Icon getSdkIcon(Sdk sdk) {
return sdk.getSdkType().getIcon();
}
}
| platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/SdkListCellRenderer.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.projectRoots.impl;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.ui.HtmlListCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import javax.swing.*;
/**
* @author yole
*/
public class SdkListCellRenderer extends HtmlListCellRenderer<Sdk> {
private String myNullText = "";
private boolean myShowHomePath;
public SdkListCellRenderer(final ListCellRenderer listCellRenderer) {
super(listCellRenderer);
}
public SdkListCellRenderer(final String nullText, final ListCellRenderer listCellRenderer) {
super(listCellRenderer);
myNullText = nullText;
}
public SdkListCellRenderer(final String nullText, final boolean showHomePath, final ListCellRenderer listCellRenderer) {
super(listCellRenderer);
myNullText = nullText;
myShowHomePath = showHomePath;
}
@Override
protected void doCustomize(final JList list, final Sdk sdk, final int index, final boolean selected, final boolean hasFocus) {
if (sdk != null) {
// icon
setIcon(sdk.getSdkType().getIcon());
// text
append(sdk.getName());
if (myShowHomePath) {
append(" (" + FileUtil.toSystemDependentName(sdk.getHomePath()) + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES);
}
}
else {
append(myNullText);
}
}
}
| sdk icon customization
| platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/SdkListCellRenderer.java | sdk icon customization | <ide><path>latform/lang-impl/src/com/intellij/openapi/projectRoots/impl/SdkListCellRenderer.java
<ide> /*
<del> * Copyright 2000-2009 JetBrains s.r.o.
<add> * Copyright 2000-2012 JetBrains s.r.o.
<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> protected void doCustomize(final JList list, final Sdk sdk, final int index, final boolean selected, final boolean hasFocus) {
<ide> if (sdk != null) {
<ide> // icon
<del> setIcon(sdk.getSdkType().getIcon());
<add> setIcon(getSdkIcon(sdk));
<ide> // text
<ide> append(sdk.getName());
<ide> if (myShowHomePath) {
<ide> append(myNullText);
<ide> }
<ide> }
<add>
<add> protected Icon getSdkIcon(Sdk sdk) {
<add> return sdk.getSdkType().getIcon();
<add> }
<ide> } |
|
Java | apache-2.0 | 6832a519a8312eca05345ab569809022c93d57fd | 0 | spring-projects/spring-social,royclarkson/spring-social,royclarkson/spring-social,okohub/spring-social,domix/spring-social,wilkinsona/spring-social,wendelas/spring-social,domix/spring-social,wilkinsona/spring-social,wooder79/spring-social_SOCIAL-196,codeconsole/spring-social,spring-projects/spring-social,Turbots/spring-social,shanika/spring-social,wooder79/spring-social_SOCIAL-196,codeconsole/spring-social,molindo/spring-social,shanika/spring-social,wendelas/spring-social,okohub/spring-social,Turbots/spring-social,molindo/spring-social | /*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.social.connect;
import java.util.Set;
/**
* A data access interface for managing a global store of users connections to service providers.
* Provides data access operations that apply across multiple user records.
* Also acts as a factory for a user-specific {@link ConnectionRepository}.
* @author Keith Donald
* @see ConnectionRepository
*/
public interface UsersConnectionRepository {
/**
* Find the id of the <i>single</i> user that has the given {@link Connection}.
* Used to support the ProviderSignIn scenario where the user id returned is used to sign a local application user in using his or her provider account.
* Returns null if there is not exactly one local user connected to the provider user.
* May never return null if this method implicitly creates a user account from the connection if no such user account already exists.
* @param connection the service provider connection resulting from the provider sign-in attempt
*/
String findUserIdWithConnection(Connection<?> connection);
/**
* Find the ids of the users who are connected to the specific provider user accounts.
* @param providerId the provider id, e.g. "facebook"
* @param providerUserIds the set of provider user ids e.g. ("125600", "131345", "54321").
* @return the set of user ids connected to those service provider users, or empty if none.
*/
Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds);
/**
* Create a single-user {@link ConnectionRepository} instance for the user assigned the given id.
* All operations on the returned repository instance are relative to the user.
* @param userId the id of the local user account.
* @return the ConnectionRepository, exposing a number of operations for accessing and updating the given user's provider connections.
*/
ConnectionRepository createConnectionRepository(String userId);
}
| spring-social-core/src/main/java/org/springframework/social/connect/UsersConnectionRepository.java | /*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.social.connect;
import java.util.Set;
/**
* A data access interface for managing a global store of LocalUser-to-ServiceProviderUser Connections.
* Provides data access operations that apply across multiple local user records.
* Also acts as a factory for a local-user-specific {@link ConnectionRepository}.
* @author Keith Donald
* @see ConnectionRepository
*/
public interface UsersConnectionRepository {
/**
* Find the id of the <i>single</i> local user that has the given {@link Connection}.
* Used to support the ProviderSignIn scenario where the user id returned is used to sign a local application user in using his or her provider account.
* Returns null if there is not exactly one local user connected to the provider user.
* May never return null if this method implicitly creates a local user account from the connection if no such local account already exists.
* @param connection the service provider connection resulting from the provider sign-in attempt
*/
String findUserIdWithConnection(Connection<?> connection);
/**
* Find the ids of the local users who are connected to the specific provider user accounts.
* @param providerId the provider id, e.g. "facebook"
* @param providerUserIds the set of provider user ids e.g. ("125600", "131345", "54321").
* @return the set of local user ids connected to those service provider users, or empty if none.
*/
Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds);
/**
* Create a single-user {@link ConnectionRepository} instance for the local user assigned the given id.
* All operations on the returned repository instance are relative to the local user.
* @param userId the id of the local user account.
* @return the ServiceProviderConnectionRepository, exposing a number of operations for accessing and updating the given local user's provider connections.
*/
ConnectionRepository createConnectionRepository(String userId);
}
| polish
| spring-social-core/src/main/java/org/springframework/social/connect/UsersConnectionRepository.java | polish | <ide><path>pring-social-core/src/main/java/org/springframework/social/connect/UsersConnectionRepository.java
<ide> import java.util.Set;
<ide>
<ide> /**
<del> * A data access interface for managing a global store of LocalUser-to-ServiceProviderUser Connections.
<del> * Provides data access operations that apply across multiple local user records.
<del> * Also acts as a factory for a local-user-specific {@link ConnectionRepository}.
<add> * A data access interface for managing a global store of users connections to service providers.
<add> * Provides data access operations that apply across multiple user records.
<add> * Also acts as a factory for a user-specific {@link ConnectionRepository}.
<ide> * @author Keith Donald
<ide> * @see ConnectionRepository
<ide> */
<ide> public interface UsersConnectionRepository {
<ide>
<ide> /**
<del> * Find the id of the <i>single</i> local user that has the given {@link Connection}.
<add> * Find the id of the <i>single</i> user that has the given {@link Connection}.
<ide> * Used to support the ProviderSignIn scenario where the user id returned is used to sign a local application user in using his or her provider account.
<ide> * Returns null if there is not exactly one local user connected to the provider user.
<del> * May never return null if this method implicitly creates a local user account from the connection if no such local account already exists.
<add> * May never return null if this method implicitly creates a user account from the connection if no such user account already exists.
<ide> * @param connection the service provider connection resulting from the provider sign-in attempt
<ide> */
<ide> String findUserIdWithConnection(Connection<?> connection);
<ide>
<ide> /**
<del> * Find the ids of the local users who are connected to the specific provider user accounts.
<add> * Find the ids of the users who are connected to the specific provider user accounts.
<ide> * @param providerId the provider id, e.g. "facebook"
<ide> * @param providerUserIds the set of provider user ids e.g. ("125600", "131345", "54321").
<del> * @return the set of local user ids connected to those service provider users, or empty if none.
<add> * @return the set of user ids connected to those service provider users, or empty if none.
<ide> */
<ide> Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds);
<ide>
<ide> /**
<del> * Create a single-user {@link ConnectionRepository} instance for the local user assigned the given id.
<del> * All operations on the returned repository instance are relative to the local user.
<add> * Create a single-user {@link ConnectionRepository} instance for the user assigned the given id.
<add> * All operations on the returned repository instance are relative to the user.
<ide> * @param userId the id of the local user account.
<del> * @return the ServiceProviderConnectionRepository, exposing a number of operations for accessing and updating the given local user's provider connections.
<add> * @return the ConnectionRepository, exposing a number of operations for accessing and updating the given user's provider connections.
<ide> */
<ide> ConnectionRepository createConnectionRepository(String userId);
<ide> |
|
Java | apache-2.0 | 5702787380bfab771d5aaada5a0b46552d7c9767 | 0 | smurn/jPLY | /*
* Copyright 2011 Stefan C. Mueller.
*
* 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.smurn.jply;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Reads elements from a PLY file in ASCII format.
*/
class AsciiElementReader implements ElementReader {
/** Type of the elements we read. */
private final ElementType type;
/** Source to read from. */
private final BufferedReader reader;
/** Number of elements. */
private final int count;
/** Index of the next row to read. */
private int nextRow = 0;
/** Flag indicating if the user closed this reader. */
private boolean closed = false;
/**
* Creates an instance.
* @param type Type of the elements to read.
* @param count Number of elements to read.
* @param reader Source to read the elements from.
*/
AsciiElementReader(final ElementType type, final int count,
final BufferedReader reader) {
if (type == null) {
throw new NullPointerException("definition must not be null.");
}
if (reader == null) {
throw new NullPointerException("reader must not be null.");
}
this.type = type;
this.count = count;
this.reader = reader;
}
@Override
public ElementType getElementType() {
return type;
}
@Override
public Element readElement() throws IOException {
if (closed) {
throw new IllegalStateException("Reader is closed.");
}
if (nextRow >= getCount()) {
return null;
}
String line = reader.readLine();
if (line == null) {
throw new IOException("Unexpected end of file.");
}
line = line.trim();
String[] parts = line.split(" +");
double[] numbers = new double[parts.length];
for (int i = 0; i < parts.length; i++) {
numbers[i] = Double.parseDouble(parts[i]);
}
// distribute the values to the properties
int pos = 0;
List<Property> properties = type.getProperties();
double[][] values = new double[properties.size()][];
for (int propI = 0; propI < properties.size(); propI++) {
Property property = properties.get(propI);
if (property instanceof ListProperty) {
if (Math.abs(Math.round(numbers[pos]) - numbers[pos]) > 1E-6){
throw new IOException("array size is not integer.");
}
int valueCount = (int) Math.round(numbers[pos++]);
values[propI] = Arrays.copyOfRange(numbers, pos,
pos + valueCount);
pos += valueCount;
} else {
values[propI] = new double[]{numbers[pos++]};
}
}
if (pos != numbers.length) {
throw new IOException(
"Invalid PLY format. To many values for an element.");
}
nextRow++;
return new Element(values, type);
}
@Override
public int getCount() {
return count;
}
@Override
public void close() throws IOException {
// Consume the remaining elements so that we
// are at the right position for the next group of elements.
while (nextRow < getCount()) {
String line = reader.readLine();
if (line == null) {
throw new IOException("Unexpected end of file.");
}
nextRow++;
}
closed = true;
}
@Override
public boolean isClosed() {
return closed;
}
}
| jply/src/main/java/org/smurn/jply/AsciiElementReader.java | /*
* Copyright 2011 Stefan C. Mueller.
*
* 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.smurn.jply;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Reads elements from a PLY file in ASCII format.
*/
class AsciiElementReader implements ElementReader {
/** Type of the elements we read. */
private final ElementType type;
/** Source to read from. */
private final BufferedReader reader;
/** Number of elements. */
private final int count;
/** Index of the next row to read. */
private int nextRow = 0;
/** Flag indicating if the user closed this reader. */
private boolean closed = false;
/**
* Creates an instance.
* @param type Type of the elements to read.
* @param count Number of elements to read.
* @param reader Source to read the elements from.
*/
AsciiElementReader(final ElementType type, final int count,
final BufferedReader reader) {
if (type == null) {
throw new NullPointerException("definition must not be null.");
}
if (reader == null) {
throw new NullPointerException("reader must not be null.");
}
this.type = type;
this.count = count;
this.reader = reader;
}
@Override
public ElementType getElementType() {
return type;
}
@Override
public Element readElement() throws IOException {
if (closed) {
throw new IllegalStateException("Reader is closed.");
}
if (nextRow >= getCount()) {
return null;
}
String line = reader.readLine();
if (line == null) {
throw new IOException("Unexpected end of file.");
}
line = line.trim();
String[] parts = line.split(" +");
double[] numbers = new double[parts.length];
for (int i = 0; i < parts.length; i++) {
numbers[i] = Double.parseDouble(parts[i]);
}
// distribute the values to the properties
int pos = 0;
List<Property> properties = type.getProperties();
double[][] values = new double[properties.size()][];
for (int propI = 0; propI < properties.size(); propI++) {
Property property = properties.get(propI);
if (property instanceof ListProperty) {
int valueCount = (int) Math.round(numbers[pos++]);
values[propI] = Arrays.copyOfRange(numbers, pos,
pos + valueCount);
pos += valueCount;
} else {
values[propI] = new double[]{numbers[pos++]};
}
}
nextRow++;
return new Element(values, type);
}
@Override
public int getCount() {
return count;
}
@Override
public void close() throws IOException {
// Consume the remaining elements so that we
// are at the right position for the next group of elements.
while (nextRow < getCount()) {
String line = reader.readLine();
if (line == null) {
throw new IOException("Unexpected end of file.");
}
nextRow++;
}
closed = true;
}
@Override
public boolean isClosed() {
return closed;
}
}
| Added some exception throwing to AsciiElementReader to find bugs in the model earlier.
Signed-off-by: Stefan C. Mueller <[email protected]>
| jply/src/main/java/org/smurn/jply/AsciiElementReader.java | Added some exception throwing to AsciiElementReader to find bugs in the model earlier. | <ide><path>ply/src/main/java/org/smurn/jply/AsciiElementReader.java
<ide>
<ide> /** Type of the elements we read. */
<ide> private final ElementType type;
<add>
<ide> /** Source to read from. */
<ide> private final BufferedReader reader;
<add>
<ide> /** Number of elements. */
<ide> private final int count;
<add>
<ide> /** Index of the next row to read. */
<ide> private int nextRow = 0;
<add>
<ide> /** Flag indicating if the user closed this reader. */
<ide> private boolean closed = false;
<ide>
<ide> for (int propI = 0; propI < properties.size(); propI++) {
<ide> Property property = properties.get(propI);
<ide> if (property instanceof ListProperty) {
<add> if (Math.abs(Math.round(numbers[pos]) - numbers[pos]) > 1E-6){
<add> throw new IOException("array size is not integer.");
<add> }
<ide> int valueCount = (int) Math.round(numbers[pos++]);
<add>
<ide> values[propI] = Arrays.copyOfRange(numbers, pos,
<ide> pos + valueCount);
<ide> pos += valueCount;
<ide> } else {
<ide> values[propI] = new double[]{numbers[pos++]};
<ide> }
<add> }
<add> if (pos != numbers.length) {
<add> throw new IOException(
<add> "Invalid PLY format. To many values for an element.");
<ide> }
<ide>
<ide> nextRow++; |
|
JavaScript | mit | b37332c783b996808428869214741b0288115415 | 0 | saravr/enhanced-wp-gallery,saravr/enhanced-wp-gallery | jQuery(function($) {
var url = ewg_data.ajax_url;
var plugins_url = ewg_data.plugins_url;
var shortcode = 'egallery'; // TBD replace shortcodes below
$(document).ready(function(e){
if (ewg_data.legacy_ss == "yes") {
console.log('Post has legacy slideshow, ignore');
return;
}
//preventing loss of focus
$(document).on('focusin', function(e) {
if ($(e.target).closest(".mce-window").length) {
e.stopImmediatePropagation();
}
});
$('#insert-my-media').click({mode: 'new'}, open_media_window);
jQuery(document).off('click', '.dashicons-edit');
jQuery(document).on('click', '.dashicons-edit', {mode: 'edit'}, open_media_window);
jQuery(document).off('click', '.dashicons-no');
jQuery(document).on('click', '.dashicons-no', delete_gallery);
});
var extractGallery = function (contents) {
var regex = /\[egallery ids=([^\]]*)\]/;
var matches = regex.exec(contents);
if (matches !== null && matches.length > 0) {
return matches[0];
}
return '';
}
var delete_gallery = function (e) {
var contents = tinyMCE.get("content").getContent();
var gallery = extractGallery(contents);
contents = contents.replace(gallery, "");
console.log('Removing gallery: ' + gallery);
tinyMCE.get("content").setContent(contents);
}
function sendSelection (mdata, object, callback) {
var sel_msg = {
'action': 'coll_info',
'postid': ewg_data.post_id,
'mdata': mdata
};
jQuery.post(url, sel_msg, function(response) {
console.log('Sent selection - response: ' + response);
var resp = JSON.parse(response);
console.log('STATUS: ' + resp.status);
console.log('IDLIST: ' + resp.idlist);
callback(resp.idlist, object);
});
}
var open_media_window = function (e) {
console.log('OPEN MEDIA WINDOW ...');
var idlist = [];
this.galleryMode = e.data.mode;
if (this.galleryMode === "edit") {
var contents = tinyMCE.get("content").getContent();
console.log('EDIT: Original contents: ' + contents);
var content = extractGallery(contents);
this.galleryContents = content;
var regex = /\[egallery ids=([^\]]*)\]/;
var matches = regex.exec(content);
if (matches !== null && matches.length > 1) {
var data = matches[1].replace(/['"]+/g, '');
idlist = data.split(",");
}
}
this.window = wp.media({
title: 'Select images for gallery',
library: {type: 'image'},
multiple: 'add',
button: {text: 'Create Gallery'}
});
var self = this;
if (this.galleryMode === "edit") {
console.log('Showing select window ...');
this.window.open();
selectHandler(self, idlist);
} else {
showSavedSelection(idlist, this);
console.log('Setting select handler ...');
this.window.on('select', function(arg) { selectHandler(self); });
this.window.open();
}
return false;
}
var showPanel = function (p) {
console.log("Showing panel: " + p);
if (p === "thumbnail") {
jQuery("#ewg-detail-panel").hide();
jQuery("#ewg-thumbnail-panel").show();
} else {
jQuery("#ewg-thumbnail-panel").hide();
jQuery("#ewg-detail-panel").show();
}
}
var removePanel = function () {
jQuery("#ewg-outer-panel").remove();
jQuery("#ewg-panel").remove();
}
var selectHandler = function (object, idlist) {
console.log('Select handler invoked ... ');
removePanel();
var dt = Date.now();
var backid = 'ewg-back-' + dt;
var backtag = '#' + backid;
var submitId = 'ewg-submit-' + dt;
var submitTag = '#' + submitId;
var titlePfx = 'ewg-title-' + dt;
var captionPfx = 'ewg-caption-' + dt;
var togglePfx = 'ewg-toggle-' + dt;
var panel = jQuery('<div id="ewg-panel"></div>');
var tnPanel = jQuery('<div id="ewg-thumbnail-panel" style="overflow-y:scroll;height:540px;"></div>');
tnPanel.sortable();
tnPanel.append("<hr style='clear:left;'/>");
//tnPanel.append("Placeholder for thumbnails");
var dtPanel = jQuery('<div id="ewg-detail-panel" style="overflow-y:scroll;height:540px;"></div>');
dtPanel.append("<hr style='clear:left;'/>");
if (idlist === undefined) {
var list = object.window.state().get('selection').toJSON();
idlist = [];
for (i = 0; i < list.length; i++) {
var id = list[i].id;
idlist.push(id);
}
}
for (i = 0; i < idlist.length; i++) {
var id = (typeof idlist[i] === "string") ? idlist[i].trim() : idlist[i];
var attObj = wp.media.attachment(id);
attObj.fetch();
var aaa = JSON.stringify(attObj); // TBD !!!
var att = JSON.parse(aaa);
var ida = '<div class="ewg-att" id="att-' + id + '" style="padding-bottom:20px;margin-left:40px;height:400px;resize:vertical;">';
var titleId = titlePfx + '-' + id;
var captionId = captionPfx + '-' + id;
var toggleId = togglePfx + '-' + id;
var url = att.sizes.thumbnail.url;
var deleteId = 'ewg-delete-' + dt + '-' + id;
var deleteTag = '#' + deleteId;
var delButton = "<div style='width:320px;height:40px;'><button class='button-primary button-small ewg-remove-button' style='float:right;margin-bottom:10px;' id='" + deleteId + "'>Remove</button></div>";
ida += '<div style="width:320px;margin-top:10px;margin-right:40px;margin-bottom:40px;float:right;">' + delButton + '<img style="float:right;" class="ewg-image" src="' + url + '"/></div>';
ida += "<div style='width:60%;margin-top:5px;'><div style='margin-top:20px;'><label style='clear:left;'><b>Title</b></label></div><br/><input id=" + titleId + " style='width:100%' type='text' value=\"" + att.title + "\"/></div>";
ida += "<div style='width:60%;margin-top:5px;'><div style='margin-top:20px;'><label style='clear:left;'><b>Caption</b></label> <a href='#' class='ewg-button' style='float:right;' id=" + toggleId + ">View Text</a></div><br/><div style='border:1px solid #ddd;'><textarea class='ewg-caption' id=" + captionId + " style='width:100%;' row=3>" + att.caption + "</textarea></div></div>";
ida += "</div>";
dtPanel.append(ida);
var tnImg = '<div style="width:120px;height:120px;display:table-cell;"><img style="margin:20px;" class="ewg-tn-image" src="' + url + '"/></div>';
tnPanel.append(tnImg);
}
dtPanel.append("<hr style='clear:left;'/>");
console.log('User selected ids: ' + idlist);
var outerPanel = jQuery('<div id="ewg-outer-panel" style="overflow-y:hidden;height:660px;background:white;"></div>');
var headingHtml = `
<div style="height:40px;padding-left:20px;width:100%;">
<div style="display:table-cell;width:89%;">
<h1>Edit Gallery</h1>
</div>
<div style="display:table-cell;width:20%;">
<a href="#" id="ewg-tile-view">Tile View</a>
<a href="#" id="ewg-detail-view">Details View</a>
</div>
</div>'
`;
var header = jQuery(headingHtml);
var buttonTitle = (object.galleryMode === "edit") ? "Update Gallery" : "Insert Gallery";
var footer = jQuery("<div style='padding-top:10px;padding-right:20px;bottom:0px;height:60px;'><button class='button-primary button-large' style='margin-left:10px;float:right;' id='" + submitId + "'>" + buttonTitle + "</button><button id='" + backid + "' class='button-primary button-large' style='margin-left:10px;float:right;'>Add Images</button></div>");
panel.append(tnPanel);
panel.append(dtPanel);
outerPanel.append(header);
outerPanel.append(panel);
outerPanel.append(footer);
jQuery(".media-modal-content").replaceWith(outerPanel);
showPanel("detail");
var tileView = jQuery("#ewg-tile-view");
tileView.off('click');
tileView.on('click', function(e) {
showPanel("thumbnail");
});
var detailView = jQuery("#ewg-detail-view");
detailView.off('click');
detailView.on('click', function(e) {
showPanel("detail");
});
for (i = 0; i < idlist.length; i++) {
var id = (typeof idlist[i] === "string") ? idlist[i].trim() : idlist[i];
tinymce.init({
selector: "#" + captionId,
menu: {},
plugins: "tabfocus,paste,media,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs",
toolbar: "bold italic | link unlink",
});
var captionId = captionPfx + '-' + id;
var toggleId = togglePfx + '-' + id;
(function(tId, cId) {
jQuery("#" + tId).on('click', function(e) {
tinyMCE.execCommand('mceToggleEditor', false, cId);
jQuery(this).text(function (i, text) {
return text === "View Text" ? "View Styled" : "View Text";
});
});
})(toggleId, captionId);
var deleteId = 'ewg-delete-' + dt + '-' + id;
var deleteTag = '#' + deleteId;
jQuery(deleteTag).off('click');
(function(idx) {
jQuery(deleteTag).click(function (e) {
jQuery("#att-" + idx).hide('slow', function() {
this.remove();
var newlist = [];
for (i = 0; i < idlist.length; i++) {
var idc = (typeof idlist[i] === "string") ?
idlist[i].trim() : idlist[i];
if (idc === idx) {
idlist.splice(i, 1);
}
}
console.log('ID list after remove: ' + idlist);
});
});
})(id);
}
console.log('Setting back handler with idlist: ' + idlist);
jQuery(backtag).off('click');
jQuery(backtag).click(function(e) { backHandler(idlist, object); });
jQuery(submitTag).off('click');
jQuery(submitTag).click(function(e) { submitHandler(dt, object); });
object.window.open();
}
var submitHandler = function (dt, object) {
var idlist = [];
divlist = jQuery("#ewg-detail-panel").children("div[id]");
for (i = 0; i < divlist.length; i++) {
var newId = divlist[i].id.replace("att-", "");
idlist.push(newId);
}
var mdata = [];
for (i = 0; i < idlist.length; i++) {
var id = (typeof idlist[i] === "string") ? idlist[i].trim() : idlist[i];
console.log('SUBMIT ID: ' + id);
var titleId = 'ewg-title-' + dt + '-' + id;
var title = jQuery("#" + titleId).val();
console.log(dt + ": title: " + title);
title = (title !== undefined) ? title : "";
var captionId = 'ewg-caption-' + dt + '-' + id;
//var caption = jQuery("#" + captionId).val();
var captionObj = tinyMCE.get(captionId);
var caption = (captionObj != null) ? captionObj.getContent() : "";
console.log(dt + ": caption: " + caption);
mdata.push({"att": id, "title": title, "caption": caption});
}
sendSelection(mdata, object, function(idlist, object) {
var gallerySC = '[egallery ids="' + idlist + '"]';
console.log('GALLERY SC: ' + gallerySC);
if (object.galleryMode === "new") {
wp.media.editor.insert(gallerySC);
} else {
var contents = tinyMCE.get("content").getContent();
console.log('Original contents: ' + contents);
var gallery = extractGallery(contents);
console.log('Replacing: ' + gallery + ' with ' + gallerySC);
contents = contents.replace(gallery, gallerySC);
tinyMCE.get("content").setContent(contents);
console.log('Loaded edited gallery: ' + contents);
}
});
removePanel();
object.window.close();
return false;
}
var backHandler = function (idlist, object) {
console.log('Back handler invoked with idlist: ' + idlist);
object.window.close();
object.window = wp.media({
title: 'Select images for gallery',
library: {type: 'image'},
multiple: 'add',
button: {text: 'Create Gallery'}
});
console.log('Setting select handler ...');
object.window.on('select', function(arg) { selectHandler(object); });
console.log('Saved for selection: ' + idlist);
showSavedSelection(idlist, object);
removePanel();
object.window.open();
}
var showSavedSelection = function (idlist, object) {
console.log('Setting OPEN handler with idlist: ' + idlist);
if (idlist === undefined) {
return;
}
var callback = function () {
console.log('Showing saved selection with idlist: ' + idlist);
var selection = object.window.state().get('selection')
for (i = 0; i < idlist.length; i++) {
id = (typeof idlist[i] === "string") ? idlist[i].trim() : idlist[i];
console.log('Preselecting id: ' + id);
var attachment = wp.media.attachment(id);
attachment.fetch();
selection.add(attachment);
}
}
object.window.on('open', callback);
}
});
| js/media_button.js | jQuery(function($) {
var url = ewg_data.ajax_url;
var plugins_url = ewg_data.plugins_url;
var shortcode = 'egallery'; // TBD replace shortcodes below
$(document).ready(function(e){
if (ewg_data.legacy_ss == "yes") {
console.log('Post has legacy slideshow, ignore');
return;
}
//preventing loss of focus
$(document).on('focusin', function(e) {
if ($(e.target).closest(".mce-window").length) {
e.stopImmediatePropagation();
}
});
$('#insert-my-media').click({mode: 'new'}, open_media_window);
jQuery(document).off('click', '.dashicons-edit');
jQuery(document).on('click', '.dashicons-edit', {mode: 'edit'}, open_media_window);
jQuery(document).off('click', '.dashicons-no');
jQuery(document).on('click', '.dashicons-no', delete_gallery);
});
var extractGallery = function (contents) {
var regex = /\[egallery ids=([^\]]*)\]/;
var matches = regex.exec(contents);
if (matches !== null && matches.length > 0) {
return matches[0];
}
return '';
}
var delete_gallery = function (e) {
var contents = tinyMCE.get("content").getContent();
var gallery = extractGallery(contents);
contents = contents.replace(gallery, "");
console.log('Removing gallery: ' + gallery);
tinyMCE.get("content").setContent(contents);
}
function sendSelection (mdata, object, callback) {
var sel_msg = {
'action': 'coll_info',
'postid': ewg_data.post_id,
'mdata': mdata
};
jQuery.post(url, sel_msg, function(response) {
console.log('Sent selection - response: ' + response);
var resp = JSON.parse(response);
console.log('STATUS: ' + resp.status);
console.log('IDLIST: ' + resp.idlist);
callback(resp.idlist, object);
});
}
var open_media_window = function (e) {
console.log('OPEN MEDIA WINDOW ...');
var idlist = [];
this.galleryMode = e.data.mode;
if (this.galleryMode === "edit") {
var contents = tinyMCE.get("content").getContent();
console.log('EDIT: Original contents: ' + contents);
var content = extractGallery(contents);
this.galleryContents = content;
var regex = /\[egallery ids=([^\]]*)\]/;
var matches = regex.exec(content);
if (matches !== null && matches.length > 1) {
var data = matches[1].replace(/['"]+/g, '');
idlist = data.split(",");
}
}
this.window = wp.media({
title: 'Select images for gallery',
library: {type: 'image'},
multiple: 'add',
button: {text: 'Create Gallery'}
});
var self = this;
if (this.galleryMode === "edit") {
console.log('Showing select window ...');
this.window.open();
selectHandler(self, idlist);
} else {
showSavedSelection(idlist, this);
console.log('Setting select handler ...');
this.window.on('select', function(arg) { selectHandler(self); });
this.window.open();
}
return false;
}
var selectHandler = function (object, idlist) {
console.log('Select handler invoked ... ');
var dt = Date.now();
var backid = 'ewg-back-' + dt;
var backtag = '#' + backid;
var submitId = 'ewg-submit-' + dt;
var submitTag = '#' + submitId;
var titlePfx = 'ewg-title-' + dt;
var captionPfx = 'ewg-caption-' + dt;
var togglePfx = 'ewg-toggle-' + dt;
console.log('BACKTAG: ' + backtag);
var panel = jQuery('<div id="newgl" style="overflow-y:scroll;height:540px;"></div>');
panel.sortable({
stop: function (event, ui) {
var lst = jQuery("#newgl .ewg-caption")
for (i = 0; i < lst.length; i++) {
var editorId = lst[i].id;
tinyMCE.get(editorId).remove();
tinyMCE.execCommand("mceAddEditor", false, editorId);
}
}
});
panel.append("<hr style='clear:left;'/>");
if (idlist === undefined) {
var list = object.window.state().get('selection').toJSON();
idlist = [];
for (i = 0; i < list.length; i++) {
var id = list[i].id;
idlist.push(id);
}
}
for (i = 0; i < idlist.length; i++) {
var id = (typeof idlist[i] === "string") ? idlist[i].trim() : idlist[i];
var attObj = wp.media.attachment(id);
attObj.fetch();
var aaa = JSON.stringify(attObj); // TBD !!!
var att = JSON.parse(aaa);
var ida = '<div class="ewg-att" id="att-' + id + '" style="padding-bottom:20px;margin-left:40px;height:400px;resize:vertical;">';
var titleId = titlePfx + '-' + id;
var captionId = captionPfx + '-' + id;
var toggleId = togglePfx + '-' + id;
var url = att.sizes.thumbnail.url;
var deleteId = 'ewg-delete-' + dt + '-' + id;
var deleteTag = '#' + deleteId;
var delButton = "<div style='width:320px;'><button class='button-primary button-small ewg-remove-button' style='float:right;margin-bottom:10px;' id='" + deleteId + "'>Remove</button></div>";
ida += '<div style="width:320px;margin-top:10px;margin-right:40px;margin-bottom:40px;float:right;">' + delButton + '<img style="float:right;" class="ewg-image" src="' + url + '"/></div>';
ida += "<div style='width:60%;margin-top:5px;'><div style='margin-top:20px;'><label style='clear:left;'><b>Title</b></label></div><br/><input id=" + titleId + " style='width:100%' type='text' value=\"" + att.title + "\"/></div>";
ida += "<div style='width:60%;margin-top:5px;'><div style='margin-top:20px;'><label style='clear:left;'><b>Caption</b></label> <a href='#' class='ewg-button' style='float:right;' id=" + toggleId + ">View Text</a></div><br/><div style='border:1px solid #ddd;'><textarea class='ewg-caption' id=" + captionId + " style='width:100%;' row=3>" + att.caption + "</textarea></div></div>";
ida += "</div>";
panel.append(ida);
}
panel.append("<hr style='clear:left;'/>");
console.log('User selected ids: ' + idlist);
var outerPanel = jQuery('<div style="overflow-y:hidden;height:660px;background:white;"></div>');
var header = jQuery('<div style="height:40px;padding-left:20px;"><h1>Edit Gallery</h1></div>');
var buttonTitle = (object.galleryMode === "edit") ? "Update Gallery" : "Insert Gallery";
var footer = jQuery("<div style='padding-top:10px;padding-right:20px;bottom:0px;height:60px;'><button class='button-primary button-large' style='margin-left:10px;float:right;' id='" + submitId + "'>" + buttonTitle + "</button><button id='" + backid + "' class='button-primary button-large' style='margin-left:10px;float:right;'>Add Images</button></div>");
outerPanel.append(header);
outerPanel.append(panel);
outerPanel.append(footer);
jQuery(".media-modal-content").replaceWith(outerPanel);
for (i = 0; i < idlist.length; i++) {
var id = (typeof idlist[i] === "string") ? idlist[i].trim() : idlist[i];
tinymce.init({
selector: "#" + captionId,
menu: {},
plugins: "tabfocus,paste,media,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs",
toolbar: "bold italic | link unlink",
});
var captionId = captionPfx + '-' + id;
var toggleId = togglePfx + '-' + id;
(function(tId, cId) {
jQuery("#" + tId).on('click', function(e) {
tinyMCE.execCommand('mceToggleEditor', false, cId);
jQuery(this).text(function (i, text) {
return text === "View Text" ? "View Styled" : "View Text";
});
});
})(toggleId, captionId);
var deleteId = 'ewg-delete-' + dt + '-' + id;
var deleteTag = '#' + deleteId;
jQuery(deleteTag).off('click');
(function(idx) {
jQuery(deleteTag).click(function (e) {
jQuery("#att-" + idx).hide('slow', function() {
this.remove();
var newlist = [];
for (i = 0; i < idlist.length; i++) {
var idc = (typeof idlist[i] === "string") ?
idlist[i].trim() : idlist[i];
if (idc === idx) {
idlist.splice(i, 1);
}
}
console.log('ID list after remove: ' + idlist);
});
});
})(id);
}
console.log('Setting back handler with idlist: ' + idlist);
jQuery(backtag).off('click');
jQuery(backtag).click(function(e) { backHandler(idlist, object); });
jQuery(submitTag).off('click');
jQuery(submitTag).click(function(e) { submitHandler(dt, object); });
object.window.open();
}
var submitHandler = function (dt, object) {
var idlist = [];
divlist = jQuery("#newgl").children("div[id]");
for (i = 0; i < divlist.length; i++) {
var newId = divlist[i].id.replace("att-", "");
idlist.push(newId);
}
var mdata = [];
for (i = 0; i < idlist.length; i++) {
var id = (typeof idlist[i] === "string") ? idlist[i].trim() : idlist[i];
console.log('SUBMIT ID: ' + id);
var titleId = 'ewg-title-' + dt + '-' + id;
var title = jQuery("#" + titleId).val();
console.log(dt + ": title: " + title);
title = (title !== undefined) ? title : "";
var captionId = 'ewg-caption-' + dt + '-' + id;
//var caption = jQuery("#" + captionId).val();
var captionObj = tinyMCE.get(captionId);
var caption = (captionObj != null) ? captionObj.getContent() : "";
console.log(dt + ": caption: " + caption);
mdata.push({"att": id, "title": title, "caption": caption});
}
sendSelection(mdata, object, function(idlist, object) {
var gallerySC = '[egallery ids="' + idlist + '"]';
console.log('GALLERY SC: ' + gallerySC);
if (object.galleryMode === "new") {
wp.media.editor.insert(gallerySC);
} else {
var contents = tinyMCE.get("content").getContent();
console.log('Original contents: ' + contents);
var gallery = extractGallery(contents);
console.log('Replacing: ' + gallery + ' with ' + gallerySC);
contents = contents.replace(gallery, gallerySC);
tinyMCE.get("content").setContent(contents);
console.log('Loaded edited gallery: ' + contents);
}
});
jQuery("#newgl").remove();
object.window.close();
return false;
}
var backHandler = function (idlist, object) {
console.log('Back handler invoked with idlist: ' + idlist);
object.window.close();
object.window = wp.media({
title: 'Select images for gallery',
library: {type: 'image'},
multiple: 'add',
button: {text: 'Create Gallery'}
});
console.log('Setting select handler ...');
object.window.on('select', function(arg) { selectHandler(object); });
console.log('Saved for selection: ' + idlist);
showSavedSelection(idlist, object);
jQuery("#newgl").remove();
object.window.open();
}
var showSavedSelection = function (idlist, object) {
console.log('Setting OPEN handler with idlist: ' + idlist);
if (idlist === undefined) {
return;
}
//var self = object;
var callback = function () {
console.log('Showing saved selection with idlist: ' + idlist);
var selection = object.window.state().get('selection')
for (i = 0; i < idlist.length; i++) {
id = (typeof idlist[i] === "string") ? idlist[i].trim() : idlist[i];
console.log('Preselecting id: ' + id);
var attachment = wp.media.attachment(id);
attachment.fetch();
selection.add(attachment);
}
}
object.window.on('open', callback);
}
});
| Added basic tile view support
| js/media_button.js | Added basic tile view support | <ide><path>s/media_button.js
<ide> return false;
<ide> }
<ide>
<add> var showPanel = function (p) {
<add>
<add> console.log("Showing panel: " + p);
<add> if (p === "thumbnail") {
<add> jQuery("#ewg-detail-panel").hide();
<add> jQuery("#ewg-thumbnail-panel").show();
<add> } else {
<add> jQuery("#ewg-thumbnail-panel").hide();
<add> jQuery("#ewg-detail-panel").show();
<add> }
<add> }
<add>
<add> var removePanel = function () {
<add>
<add> jQuery("#ewg-outer-panel").remove();
<add> jQuery("#ewg-panel").remove();
<add> }
<add>
<ide> var selectHandler = function (object, idlist) {
<ide>
<ide> console.log('Select handler invoked ... ');
<add> removePanel();
<ide>
<ide> var dt = Date.now();
<ide> var backid = 'ewg-back-' + dt;
<ide> var captionPfx = 'ewg-caption-' + dt;
<ide> var togglePfx = 'ewg-toggle-' + dt;
<ide>
<del> console.log('BACKTAG: ' + backtag);
<del> var panel = jQuery('<div id="newgl" style="overflow-y:scroll;height:540px;"></div>');
<del> panel.sortable({
<del> stop: function (event, ui) {
<del> var lst = jQuery("#newgl .ewg-caption")
<del> for (i = 0; i < lst.length; i++) {
<del> var editorId = lst[i].id;
<del> tinyMCE.get(editorId).remove();
<del> tinyMCE.execCommand("mceAddEditor", false, editorId);
<del> }
<del> }
<del> });
<del> panel.append("<hr style='clear:left;'/>");
<add> var panel = jQuery('<div id="ewg-panel"></div>');
<add> var tnPanel = jQuery('<div id="ewg-thumbnail-panel" style="overflow-y:scroll;height:540px;"></div>');
<add> tnPanel.sortable();
<add> tnPanel.append("<hr style='clear:left;'/>");
<add> //tnPanel.append("Placeholder for thumbnails");
<add>
<add> var dtPanel = jQuery('<div id="ewg-detail-panel" style="overflow-y:scroll;height:540px;"></div>');
<add> dtPanel.append("<hr style='clear:left;'/>");
<ide>
<ide> if (idlist === undefined) {
<ide> var list = object.window.state().get('selection').toJSON();
<ide>
<ide> var deleteId = 'ewg-delete-' + dt + '-' + id;
<ide> var deleteTag = '#' + deleteId;
<del> var delButton = "<div style='width:320px;'><button class='button-primary button-small ewg-remove-button' style='float:right;margin-bottom:10px;' id='" + deleteId + "'>Remove</button></div>";
<add> var delButton = "<div style='width:320px;height:40px;'><button class='button-primary button-small ewg-remove-button' style='float:right;margin-bottom:10px;' id='" + deleteId + "'>Remove</button></div>";
<ide>
<ide> ida += '<div style="width:320px;margin-top:10px;margin-right:40px;margin-bottom:40px;float:right;">' + delButton + '<img style="float:right;" class="ewg-image" src="' + url + '"/></div>';
<ide> ida += "<div style='width:60%;margin-top:5px;'><div style='margin-top:20px;'><label style='clear:left;'><b>Title</b></label></div><br/><input id=" + titleId + " style='width:100%' type='text' value=\"" + att.title + "\"/></div>";
<ide> ida += "<div style='width:60%;margin-top:5px;'><div style='margin-top:20px;'><label style='clear:left;'><b>Caption</b></label> <a href='#' class='ewg-button' style='float:right;' id=" + toggleId + ">View Text</a></div><br/><div style='border:1px solid #ddd;'><textarea class='ewg-caption' id=" + captionId + " style='width:100%;' row=3>" + att.caption + "</textarea></div></div>";
<ide>
<ide> ida += "</div>";
<del> panel.append(ida);
<del> }
<del>
<del> panel.append("<hr style='clear:left;'/>");
<add> dtPanel.append(ida);
<add>
<add> var tnImg = '<div style="width:120px;height:120px;display:table-cell;"><img style="margin:20px;" class="ewg-tn-image" src="' + url + '"/></div>';
<add> tnPanel.append(tnImg);
<add> }
<add>
<add> dtPanel.append("<hr style='clear:left;'/>");
<ide>
<ide> console.log('User selected ids: ' + idlist);
<ide>
<del> var outerPanel = jQuery('<div style="overflow-y:hidden;height:660px;background:white;"></div>');
<del> var header = jQuery('<div style="height:40px;padding-left:20px;"><h1>Edit Gallery</h1></div>');
<add> var outerPanel = jQuery('<div id="ewg-outer-panel" style="overflow-y:hidden;height:660px;background:white;"></div>');
<add> var headingHtml = `
<add><div style="height:40px;padding-left:20px;width:100%;">
<add> <div style="display:table-cell;width:89%;">
<add> <h1>Edit Gallery</h1>
<add> </div>
<add> <div style="display:table-cell;width:20%;">
<add> <a href="#" id="ewg-tile-view">Tile View</a>
<add>
<add> <a href="#" id="ewg-detail-view">Details View</a>
<add> </div>
<add></div>'
<add>`;
<add> var header = jQuery(headingHtml);
<ide>
<ide> var buttonTitle = (object.galleryMode === "edit") ? "Update Gallery" : "Insert Gallery";
<ide>
<ide> var footer = jQuery("<div style='padding-top:10px;padding-right:20px;bottom:0px;height:60px;'><button class='button-primary button-large' style='margin-left:10px;float:right;' id='" + submitId + "'>" + buttonTitle + "</button><button id='" + backid + "' class='button-primary button-large' style='margin-left:10px;float:right;'>Add Images</button></div>");
<add>
<add> panel.append(tnPanel);
<add> panel.append(dtPanel);
<ide>
<ide> outerPanel.append(header);
<ide> outerPanel.append(panel);
<ide> outerPanel.append(footer);
<ide>
<ide> jQuery(".media-modal-content").replaceWith(outerPanel);
<add> showPanel("detail");
<add>
<add> var tileView = jQuery("#ewg-tile-view");
<add> tileView.off('click');
<add> tileView.on('click', function(e) {
<add> showPanel("thumbnail");
<add> });
<add>
<add> var detailView = jQuery("#ewg-detail-view");
<add> detailView.off('click');
<add> detailView.on('click', function(e) {
<add> showPanel("detail");
<add> });
<ide>
<ide> for (i = 0; i < idlist.length; i++) {
<ide> var id = (typeof idlist[i] === "string") ? idlist[i].trim() : idlist[i];
<ide> var submitHandler = function (dt, object) {
<ide>
<ide> var idlist = [];
<del> divlist = jQuery("#newgl").children("div[id]");
<add> divlist = jQuery("#ewg-detail-panel").children("div[id]");
<ide> for (i = 0; i < divlist.length; i++) {
<ide> var newId = divlist[i].id.replace("att-", "");
<ide> idlist.push(newId);
<ide> }
<ide> });
<ide>
<del> jQuery("#newgl").remove();
<add> removePanel();
<ide> object.window.close();
<ide> return false;
<ide> }
<ide> object.window.on('select', function(arg) { selectHandler(object); });
<ide> console.log('Saved for selection: ' + idlist);
<ide> showSavedSelection(idlist, object);
<del> jQuery("#newgl").remove();
<add> removePanel();
<ide> object.window.open();
<ide> }
<ide>
<ide> return;
<ide> }
<ide>
<del> //var self = object;
<ide> var callback = function () {
<ide> console.log('Showing saved selection with idlist: ' + idlist);
<ide> var selection = object.window.state().get('selection') |
|
Java | apache-2.0 | 8a12343a7d949d3c75ee5acb8151e4a21e6f9da1 | 0 | tipsy/javalin,tipsy/javalin,tipsy/javalin,tipsy/javalin | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin;
/**
* A listener for use with {@link Javalin#event}.
* Is triggered by different events in the app lifecycle.
*/
@FunctionalInterface
public interface EventListener {
void handleEvent() throws Exception;
}
| src/main/java/io/javalin/EventListener.java | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin;
/**
* A listener for use with {@link Javalin#event}.
* Is triggered by different events in the app lifecycle.
*/
@FunctionalInterface
public interface EventListener {
void handleEvent();
}
| [core] Allow event handlers to throw checked exceptions (#334)
https://github.com/tipsy/javalin/issues/333#issuecomment-414767860 | src/main/java/io/javalin/EventListener.java | [core] Allow event handlers to throw checked exceptions (#334) | <ide><path>rc/main/java/io/javalin/EventListener.java
<ide> */
<ide> @FunctionalInterface
<ide> public interface EventListener {
<del> void handleEvent();
<add> void handleEvent() throws Exception;
<ide> } |
|
Java | apache-2.0 | 3059b251d8f37456c5761ecaf73fe6c0c5a59067 | 0 | ucare-uchicago/hadoop,ucare-uchicago/hadoop,xiao-chen/hadoop,xiao-chen/hadoop,dennishuo/hadoop,lukmajercak/hadoop,steveloughran/hadoop,ronny-macmaster/hadoop,979969786/hadoop,dierobotsdie/hadoop,plusplusjiajia/hadoop,huafengw/hadoop,wwjiang007/hadoop,steveloughran/hadoop,dennishuo/hadoop,ronny-macmaster/hadoop,legend-hua/hadoop,plusplusjiajia/hadoop,soumabrata-chakraborty/hadoop,wenxinhe/hadoop,xiao-chen/hadoop,huafengw/hadoop,WIgor/hadoop,wenxinhe/hadoop,ChetnaChaudhari/hadoop,JingchengDu/hadoop,apurtell/hadoop,GeLiXin/hadoop,littlezhou/hadoop,WIgor/hadoop,ctrezzo/hadoop,nandakumar131/hadoop,soumabrata-chakraborty/hadoop,szegedim/hadoop,lukmajercak/hadoop,Ethanlm/hadoop,ChetnaChaudhari/hadoop,legend-hua/hadoop,Ethanlm/hadoop,ctrezzo/hadoop,apache/hadoop,ChetnaChaudhari/hadoop,dierobotsdie/hadoop,littlezhou/hadoop,bitmybytes/hadoop,apache/hadoop,979969786/hadoop,mapr/hadoop-common,ctrezzo/hadoop,wenxinhe/hadoop,lukmajercak/hadoop,szegedim/hadoop,littlezhou/hadoop,JingchengDu/hadoop,apache/hadoop,ChetnaChaudhari/hadoop,wwjiang007/hadoop,Ethanlm/hadoop,mapr/hadoop-common,dennishuo/hadoop,szegedim/hadoop,wwjiang007/hadoop,nandakumar131/hadoop,nandakumar131/hadoop,littlezhou/hadoop,apurtell/hadoop,ctrezzo/hadoop,GeLiXin/hadoop,dierobotsdie/hadoop,xiao-chen/hadoop,szegedim/hadoop,dennishuo/hadoop,huafengw/hadoop,wenxinhe/hadoop,ronny-macmaster/hadoop,littlezhou/hadoop,littlezhou/hadoop,steveloughran/hadoop,ctrezzo/hadoop,nandakumar131/hadoop,bitmybytes/hadoop,dierobotsdie/hadoop,Ethanlm/hadoop,Ethanlm/hadoop,apache/hadoop,wwjiang007/hadoop,dennishuo/hadoop,mapr/hadoop-common,plusplusjiajia/hadoop,GeLiXin/hadoop,bitmybytes/hadoop,mapr/hadoop-common,lukmajercak/hadoop,JingchengDu/hadoop,979969786/hadoop,steveloughran/hadoop,GeLiXin/hadoop,ctrezzo/hadoop,Ethanlm/hadoop,huafengw/hadoop,lukmajercak/hadoop,ChetnaChaudhari/hadoop,ronny-macmaster/hadoop,soumabrata-chakraborty/hadoop,legend-hua/hadoop,plusplusjiajia/hadoop,ucare-uchicago/hadoop,ChetnaChaudhari/hadoop,mapr/hadoop-common,soumabrata-chakraborty/hadoop,979969786/hadoop,legend-hua/hadoop,apache/hadoop,mapr/hadoop-common,bitmybytes/hadoop,plusplusjiajia/hadoop,JingchengDu/hadoop,979969786/hadoop,huafengw/hadoop,soumabrata-chakraborty/hadoop,WIgor/hadoop,dierobotsdie/hadoop,wwjiang007/hadoop,979969786/hadoop,WIgor/hadoop,GeLiXin/hadoop,xiao-chen/hadoop,legend-hua/hadoop,WIgor/hadoop,szegedim/hadoop,apurtell/hadoop,littlezhou/hadoop,nandakumar131/hadoop,WIgor/hadoop,lukmajercak/hadoop,GeLiXin/hadoop,steveloughran/hadoop,dierobotsdie/hadoop,JingchengDu/hadoop,JingchengDu/hadoop,apurtell/hadoop,soumabrata-chakraborty/hadoop,wenxinhe/hadoop,nandakumar131/hadoop,wenxinhe/hadoop,szegedim/hadoop,ronny-macmaster/hadoop,wwjiang007/hadoop,bitmybytes/hadoop,wwjiang007/hadoop,ChetnaChaudhari/hadoop,JingchengDu/hadoop,huafengw/hadoop,ctrezzo/hadoop,ucare-uchicago/hadoop,ronny-macmaster/hadoop,nandakumar131/hadoop,soumabrata-chakraborty/hadoop,steveloughran/hadoop,Ethanlm/hadoop,lukmajercak/hadoop,979969786/hadoop,ronny-macmaster/hadoop,ucare-uchicago/hadoop,dennishuo/hadoop,steveloughran/hadoop,dennishuo/hadoop,huafengw/hadoop,legend-hua/hadoop,apurtell/hadoop,apache/hadoop,legend-hua/hadoop,ucare-uchicago/hadoop,apurtell/hadoop,xiao-chen/hadoop,szegedim/hadoop,xiao-chen/hadoop,dierobotsdie/hadoop,apurtell/hadoop,bitmybytes/hadoop,WIgor/hadoop,GeLiXin/hadoop,apache/hadoop,wenxinhe/hadoop,ucare-uchicago/hadoop,plusplusjiajia/hadoop,mapr/hadoop-common,bitmybytes/hadoop,plusplusjiajia/hadoop | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Supplier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.ChecksumException;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.UnresolvedLinkException;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSInputStream;
import org.apache.hadoop.hdfs.DFSOutputStream;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdfs.StripedFileTestUtil;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks;
import org.apache.hadoop.hdfs.protocol.DatanodeAdminProperties;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.LocatedStripedBlock;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockCollection;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
import org.apache.hadoop.hdfs.server.blockmanagement.CombinedHostFileManager;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager;
import org.apache.hadoop.hdfs.server.blockmanagement.HostConfigManager;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
import org.apache.hadoop.hdfs.server.namenode.NamenodeFsck.Result;
import org.apache.hadoop.hdfs.server.namenode.NamenodeFsck.ReplicationResult;
import org.apache.hadoop.hdfs.server.namenode.NamenodeFsck.ErasureCodingResult;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.hdfs.tools.DFSck;
import org.apache.hadoop.hdfs.util.HostsFileWriter;
import org.apache.hadoop.hdfs.util.StripedBlockUtil;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.net.NetworkTopology;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.Sets;
/**
* A JUnit test for doing fsck.
*/
public class TestFsck {
private static final Log LOG =
LogFactory.getLog(TestFsck.class.getName());
static final String AUDITLOG_FILE =
GenericTestUtils.getTempPath("TestFsck-audit.log");
// Pattern for:
// allowed=true ugi=name ip=/address cmd=FSCK src=/ dst=null perm=null
static final Pattern FSCK_PATTERN = Pattern.compile(
"allowed=.*?\\s" +
"ugi=.*?\\s" +
"ip=/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\s" +
"cmd=fsck\\ssrc=\\/\\sdst=null\\s" +
"perm=null\\s" + "proto=.*");
static final Pattern GET_FILE_INFO_PATTERN = Pattern.compile(
"allowed=.*?\\s" +
"ugi=.*?\\s" +
"ip=/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\s" +
"cmd=getfileinfo\\ssrc=\\/\\sdst=null\\s" +
"perm=null\\s" + "proto=.*");
static final Pattern NUM_MISSING_BLOCKS_PATTERN = Pattern.compile(
".*Missing blocks:\t\t([0123456789]*).*");
static final Pattern NUM_CORRUPT_BLOCKS_PATTERN = Pattern.compile(
".*Corrupt blocks:\t\t([0123456789]*).*");
private static final String LINE_SEPARATOR =
System.getProperty("line.separator");
static String runFsck(Configuration conf, int expectedErrCode,
boolean checkErrorCode, String... path)
throws Exception {
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bStream, true);
GenericTestUtils.setLogLevel(FSPermissionChecker.LOG, Level.ALL);
int errCode = ToolRunner.run(new DFSck(conf, out), path);
if (checkErrorCode) {
assertEquals(expectedErrCode, errCode);
}
GenericTestUtils.setLogLevel(FSPermissionChecker.LOG, Level.INFO);
LOG.info("OUTPUT = " + bStream.toString());
return bStream.toString();
}
private MiniDFSCluster cluster = null;
private Configuration conf = null;
@Before
public void setUp() throws Exception {
conf = new Configuration();
}
@After
public void tearDown() throws Exception {
shutdownCluster();
}
private void shutdownCluster() throws Exception {
if (cluster != null) {
cluster.shutdown();
}
}
/** do fsck. */
@Test
public void testFsck() throws Exception {
DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck").
setNumFiles(20).build();
FileSystem fs = null;
final long precision = 1L;
conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY,
precision);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
fs = cluster.getFileSystem();
final String fileName = "/srcdat";
util.createFiles(fs, fileName);
util.waitReplication(fs, fileName, (short)3);
final Path file = new Path(fileName);
long aTime = fs.getFileStatus(file).getAccessTime();
Thread.sleep(precision);
setupAuditLogs();
String outStr = runFsck(conf, 0, true, "/");
verifyAuditLogs();
assertEquals(aTime, fs.getFileStatus(file).getAccessTime());
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
shutdownCluster();
// restart the cluster; bring up namenode but not the data nodes
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0).format(false).build();
outStr = runFsck(conf, 1, true, "/");
// expect the result is corrupt
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
System.out.println(outStr);
// bring up data nodes & cleanup cluster
cluster.startDataNodes(conf, 4, true, null, null);
cluster.waitActive();
cluster.waitClusterUp();
fs = cluster.getFileSystem();
util.cleanup(fs, "/srcdat");
}
/** Sets up log4j logger for auditlogs. */
private void setupAuditLogs() throws IOException {
File file = new File(AUDITLOG_FILE);
if (file.exists()) {
file.delete();
}
Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
logger.setLevel(Level.INFO);
PatternLayout layout = new PatternLayout("%m%n");
RollingFileAppender appender =
new RollingFileAppender(layout, AUDITLOG_FILE);
logger.addAppender(appender);
}
private void verifyAuditLogs() throws IOException {
// Turn off the logs
Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
logger.setLevel(Level.OFF);
BufferedReader reader = null;
try {
// Audit log should contain one getfileinfo and one fsck
reader = new BufferedReader(new FileReader(AUDITLOG_FILE));
String line;
// one extra getfileinfo stems from resolving the path
//
for (int i = 0; i < 2; i++) {
line = reader.readLine();
assertNotNull(line);
assertTrue("Expected getfileinfo event not found in audit log",
GET_FILE_INFO_PATTERN.matcher(line).matches());
}
line = reader.readLine();
assertNotNull(line);
assertTrue("Expected fsck event not found in audit log", FSCK_PATTERN
.matcher(line).matches());
assertNull("Unexpected event in audit log", reader.readLine());
} finally {
// Close the reader and remove the appender to release the audit log file
// handle after verifying the content of the file.
if (reader != null) {
reader.close();
}
if (logger != null) {
logger.removeAllAppenders();
}
}
}
@Test
public void testFsckNonExistent() throws Exception {
DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck").
setNumFiles(20).build();
FileSystem fs = null;
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
fs = cluster.getFileSystem();
util.createFiles(fs, "/srcdat");
util.waitReplication(fs, "/srcdat", (short)3);
String outStr = runFsck(conf, 0, true, "/non-existent");
assertEquals(-1, outStr.indexOf(NamenodeFsck.HEALTHY_STATUS));
System.out.println(outStr);
util.cleanup(fs, "/srcdat");
}
/** Test fsck with permission set on inodes. */
@Test
public void testFsckPermission() throws Exception {
final DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(20).build();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
// Create a cluster with the current user, write some files
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
final MiniDFSCluster c2 = cluster;
final String dir = "/dfsck";
final Path dirpath = new Path(dir);
final FileSystem fs = c2.getFileSystem();
util.createFiles(fs, dir);
util.waitReplication(fs, dir, (short) 3);
fs.setPermission(dirpath, new FsPermission((short) 0700));
// run DFSck as another user, should fail with permission issue
UserGroupInformation fakeUGI = UserGroupInformation.createUserForTesting(
"ProbablyNotARealUserName", new String[] {"ShangriLa"});
fakeUGI.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
System.out.println(runFsck(conf, -1, true, dir));
return null;
}
});
// set permission and try DFSck again as the fake user, should succeed
fs.setPermission(dirpath, new FsPermission((short) 0777));
fakeUGI.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final String outStr = runFsck(conf, 0, true, dir);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
return null;
}
});
util.cleanup(fs, dir);
}
@Test
public void testFsckMove() throws Exception {
final int dfsBlockSize = 1024;
final int numDatanodes = 4;
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, dfsBlockSize);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
DFSTestUtil util = new DFSTestUtil("TestFsck", 5, 3,
(5 * dfsBlockSize) + (dfsBlockSize - 1), 5 * dfsBlockSize);
FileSystem fs = null;
cluster = new MiniDFSCluster.Builder(conf).
numDataNodes(numDatanodes).build();
String topDir = "/srcdat";
fs = cluster.getFileSystem();
cluster.waitActive();
util.createFiles(fs, topDir);
util.waitReplication(fs, topDir, (short)3);
String outStr = runFsck(conf, 0, true, "/");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
DFSClient dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
String[] fileNames = util.getFileNames(topDir);
CorruptedTestFile[] ctFiles = new CorruptedTestFile[]{
new CorruptedTestFile(fileNames[0], Sets.newHashSet(0),
dfsClient, numDatanodes, dfsBlockSize),
new CorruptedTestFile(fileNames[1], Sets.newHashSet(2, 3),
dfsClient, numDatanodes, dfsBlockSize),
new CorruptedTestFile(fileNames[2], Sets.newHashSet(4),
dfsClient, numDatanodes, dfsBlockSize),
new CorruptedTestFile(fileNames[3], Sets.newHashSet(0, 1, 2, 3),
dfsClient, numDatanodes, dfsBlockSize),
new CorruptedTestFile(fileNames[4], Sets.newHashSet(1, 2, 3, 4),
dfsClient, numDatanodes, dfsBlockSize)
};
int totalMissingBlocks = 0;
for (CorruptedTestFile ctFile : ctFiles) {
totalMissingBlocks += ctFile.getTotalMissingBlocks();
}
for (CorruptedTestFile ctFile : ctFiles) {
ctFile.removeBlocks(cluster);
}
// Wait for fsck to discover all the missing blocks
while (true) {
outStr = runFsck(conf, 1, false, "/");
String numMissing = null;
String numCorrupt = null;
for (String line : outStr.split(LINE_SEPARATOR)) {
Matcher m = NUM_MISSING_BLOCKS_PATTERN.matcher(line);
if (m.matches()) {
numMissing = m.group(1);
}
m = NUM_CORRUPT_BLOCKS_PATTERN.matcher(line);
if (m.matches()) {
numCorrupt = m.group(1);
}
if (numMissing != null && numCorrupt != null) {
break;
}
}
if (numMissing == null || numCorrupt == null) {
throw new IOException("failed to find number of missing or corrupt" +
" blocks in fsck output.");
}
if (numMissing.equals(Integer.toString(totalMissingBlocks))) {
assertTrue(numCorrupt.equals(Integer.toString(0)));
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
}
}
// Copy the non-corrupt blocks of corruptFileName to lost+found.
outStr = runFsck(conf, 1, false, "/", "-move");
LOG.info("WATERMELON: outStr = " + outStr);
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
// Make sure that we properly copied the block files from the DataNodes
// to lost+found
for (CorruptedTestFile ctFile : ctFiles) {
ctFile.checkSalvagedRemains();
}
// Fix the filesystem by removing corruptFileName
outStr = runFsck(conf, 1, true, "/", "-delete");
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
// Check to make sure we have a healthy filesystem
outStr = runFsck(conf, 0, true, "/");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
util.cleanup(fs, topDir);
}
static private class CorruptedTestFile {
final private String name;
final private Set<Integer> blocksToCorrupt;
final private DFSClient dfsClient;
final private int numDataNodes;
final private int blockSize;
final private byte[] initialContents;
CorruptedTestFile(String name, Set<Integer> blocksToCorrupt,
DFSClient dfsClient, int numDataNodes, int blockSize)
throws IOException {
this.name = name;
this.blocksToCorrupt = blocksToCorrupt;
this.dfsClient = dfsClient;
this.numDataNodes = numDataNodes;
this.blockSize = blockSize;
this.initialContents = cacheInitialContents();
}
public int getTotalMissingBlocks() {
return blocksToCorrupt.size();
}
private byte[] cacheInitialContents() throws IOException {
HdfsFileStatus status = dfsClient.getFileInfo(name);
byte[] content = new byte[(int)status.getLen()];
DFSInputStream in = null;
try {
in = dfsClient.open(name);
IOUtils.readFully(in, content, 0, content.length);
} finally {
in.close();
}
return content;
}
public void removeBlocks(MiniDFSCluster cluster)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
for (int corruptIdx : blocksToCorrupt) {
// Corrupt a block by deleting it
ExtendedBlock block = dfsClient.getNamenode().getBlockLocations(
name, blockSize * corruptIdx, Long.MAX_VALUE).get(0).getBlock();
for (int i = 0; i < numDataNodes; i++) {
File blockFile = cluster.getBlockFile(i, block);
if(blockFile != null && blockFile.exists()) {
assertTrue(blockFile.delete());
}
}
}
}
public void corruptBlocks(MiniDFSCluster cluster) throws IOException {
for (int corruptIdx : blocksToCorrupt) {
// Corrupt a block by deleting it
ExtendedBlock block = dfsClient.getNamenode().getBlockLocations(name,
blockSize * corruptIdx, Long.MAX_VALUE).get(0).getBlock();
for (int i = 0; i < numDataNodes; i++) {
File blockFile = cluster.getBlockFile(i, block);
if(blockFile != null && blockFile.exists()) {
FileOutputStream blockFileStream =
new FileOutputStream(blockFile, false);
blockFileStream.write("corrupt".getBytes());
blockFileStream.close();
LOG.info("Corrupted block file " + blockFile);
}
}
}
}
public void checkSalvagedRemains() throws IOException {
int chainIdx = 0;
HdfsFileStatus status = dfsClient.getFileInfo(name);
long length = status.getLen();
int numBlocks = (int)((length + blockSize - 1) / blockSize);
DFSInputStream in = null;
byte[] blockBuffer = new byte[blockSize];
try {
for (int blockIdx = 0; blockIdx < numBlocks; blockIdx++) {
if (blocksToCorrupt.contains(blockIdx)) {
if (in != null) {
in.close();
in = null;
}
continue;
}
if (in == null) {
in = dfsClient.open("/lost+found" + name + "/" + chainIdx);
chainIdx++;
}
int len = blockBuffer.length;
if (blockIdx == (numBlocks - 1)) {
// The last block might not be full-length
len = (int)(in.getFileLength() % blockSize);
if (len == 0) {
len = blockBuffer.length;
}
}
IOUtils.readFully(in, blockBuffer, 0, len);
int startIdx = blockIdx * blockSize;
for (int i = 0; i < len; i++) {
if (initialContents[startIdx + i] != blockBuffer[i]) {
throw new IOException("salvaged file " + name + " differed " +
"from what we expected on block " + blockIdx);
}
}
}
} finally {
IOUtils.cleanup(null, in);
}
}
}
@Test
public void testFsckMoveAndDelete() throws Exception {
final int maxMoveTries = 5;
DFSTestUtil util = new DFSTestUtil.Builder().
setName("TestFsckMoveAndDelete").setNumFiles(5).build();
FileSystem fs = null;
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
String topDir = "/srcdat";
fs = cluster.getFileSystem();
cluster.waitActive();
util.createFiles(fs, topDir);
util.waitReplication(fs, topDir, (short)3);
String outStr = runFsck(conf, 0, true, "/");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// Corrupt a block by deleting it
String[] fileNames = util.getFileNames(topDir);
DFSClient dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
String corruptFileName = fileNames[0];
ExtendedBlock block = dfsClient.getNamenode().getBlockLocations(
corruptFileName, 0, Long.MAX_VALUE).get(0).getBlock();
for (int i=0; i<4; i++) {
File blockFile = cluster.getBlockFile(i, block);
if(blockFile != null && blockFile.exists()) {
assertTrue(blockFile.delete());
}
}
// We excpect the filesystem to be corrupted
outStr = runFsck(conf, 1, false, "/");
while (!outStr.contains(NamenodeFsck.CORRUPT_STATUS)) {
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
}
outStr = runFsck(conf, 1, false, "/");
}
// After a fsck -move, the corrupted file should still exist.
for (int i = 0; i < maxMoveTries; i++) {
outStr = runFsck(conf, 1, true, "/", "-move");
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
String[] newFileNames = util.getFileNames(topDir);
boolean found = false;
for (String f : newFileNames) {
if (f.equals(corruptFileName)) {
found = true;
break;
}
}
assertTrue(found);
}
// Fix the filesystem by moving corrupted files to lost+found
outStr = runFsck(conf, 1, true, "/", "-move", "-delete");
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
// Check to make sure we have healthy filesystem
outStr = runFsck(conf, 0, true, "/");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
util.cleanup(fs, topDir);
}
@Test
public void testFsckOpenFiles() throws Exception {
DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck").
setNumFiles(4).build();
FileSystem fs = null;
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
String topDir = "/srcdat";
String randomString = "HADOOP ";
fs = cluster.getFileSystem();
cluster.waitActive();
util.createFiles(fs, topDir);
util.waitReplication(fs, topDir, (short)3);
String outStr = runFsck(conf, 0, true, "/");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// Open a file for writing and do not close for now
Path openFile = new Path(topDir + "/openFile");
FSDataOutputStream out = fs.create(openFile);
int writeCount = 0;
while (writeCount != 100) {
out.write(randomString.getBytes());
writeCount++;
}
((DFSOutputStream) out.getWrappedStream()).hflush();
// We expect the filesystem to be HEALTHY and show one open file
outStr = runFsck(conf, 0, true, topDir);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertFalse(outStr.contains("OPENFORWRITE"));
// Use -openforwrite option to list open files
outStr = runFsck(conf, 0, true, topDir, "-files", "-blocks",
"-locations", "-openforwrite");
System.out.println(outStr);
assertTrue(outStr.contains("OPENFORWRITE"));
assertTrue(outStr.contains("Under Construction Block:"));
assertTrue(outStr.contains("openFile"));
// Close the file
out.close();
// Now, fsck should show HEALTHY fs and should not show any open files
outStr = runFsck(conf, 0, true, topDir);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertFalse(outStr.contains("OPENFORWRITE"));
assertFalse(outStr.contains("Under Construction Block:"));
util.cleanup(fs, topDir);
}
@Test
public void testFsckOpenECFiles() throws Exception {
DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsckECFile").
setNumFiles(4).build();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
ErasureCodingPolicy ecPolicy =
ErasureCodingPolicyManager.getSystemDefaultPolicy();
int numAllUnits = ecPolicy.getNumDataUnits() + ecPolicy.getNumParityUnits();
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(
numAllUnits + 1).build();
FileSystem fs = null;
String topDir = "/myDir";
byte[] randomBytes = new byte[3000000];
int seed = 42;
new Random(seed).nextBytes(randomBytes);
cluster.waitActive();
fs = cluster.getFileSystem();
util.createFiles(fs, topDir);
// set topDir to EC when it has replicated files
cluster.getFileSystem().getClient().setErasureCodingPolicy(
topDir, ecPolicy);
// create a new file under topDir
DFSTestUtil.createFile(fs, new Path(topDir, "ecFile"), 1024, (short) 1, 0L);
// Open a EC file for writing and do not close for now
Path openFile = new Path(topDir + "/openECFile");
FSDataOutputStream out = fs.create(openFile);
int writeCount = 0;
while (writeCount != 300) {
out.write(randomBytes);
writeCount++;
}
// make sure the fsck can correctly handle mixed ec/replicated files
runFsck(conf, 0, true, topDir, "-files", "-blocks", "-openforwrite");
// We expect the filesystem to be HEALTHY and show one open file
String outStr = runFsck(conf, 0, true, openFile.toString(), "-files",
"-blocks", "-openforwrite");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertTrue(outStr.contains("OPENFORWRITE"));
assertTrue(outStr.contains("Live_repl=" + numAllUnits));
assertTrue(outStr.contains("Expected_repl=" + numAllUnits));
// Use -openforwrite option to list open files
outStr = runFsck(conf, 0, true, openFile.toString(), "-files", "-blocks",
"-locations", "-openforwrite", "-replicaDetails");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertTrue(outStr.contains("OPENFORWRITE"));
assertTrue(outStr.contains("Live_repl=" + numAllUnits));
assertTrue(outStr.contains("Expected_repl=" + numAllUnits));
assertTrue(outStr.contains("Under Construction Block:"));
// Close the file
out.close();
// Now, fsck should show HEALTHY fs and should not show any open files
outStr = runFsck(conf, 0, true, openFile.toString(), "-files", "-blocks",
"-locations", "-racks", "-replicaDetails");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertFalse(outStr.contains("OPENFORWRITE"));
assertFalse(outStr.contains("Under Construction Block:"));
assertFalse(outStr.contains("Expected_repl=" + numAllUnits));
assertTrue(outStr.contains("Live_repl=" + numAllUnits));
util.cleanup(fs, topDir);
}
@Test
public void testCorruptBlock() throws Exception {
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
// Set short retry timeouts so this test runs faster
conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10);
FileSystem fs = null;
DFSClient dfsClient = null;
LocatedBlocks blocks = null;
int replicaCount = 0;
Random random = new Random();
String outStr = null;
short factor = 1;
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
cluster.waitActive();
fs = cluster.getFileSystem();
Path file1 = new Path("/testCorruptBlock");
DFSTestUtil.createFile(fs, file1, 1024, factor, 0);
// Wait until file replication has completed
DFSTestUtil.waitReplication(fs, file1, factor);
ExtendedBlock block = DFSTestUtil.getFirstBlock(fs, file1);
// Make sure filesystem is in healthy state
outStr = runFsck(conf, 0, true, "/");
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// corrupt replicas
File blockFile = cluster.getBlockFile(0, block);
if (blockFile != null && blockFile.exists()) {
RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
FileChannel channel = raFile.getChannel();
String badString = "BADBAD";
int rand = random.nextInt((int) channel.size()/2);
raFile.seek(rand);
raFile.write(badString.getBytes());
raFile.close();
}
// Read the file to trigger reportBadBlocks
try {
IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(), conf,
true);
} catch (IOException ie) {
assertTrue(ie instanceof ChecksumException);
}
dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
blocks = dfsClient.getNamenode().
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
replicaCount = blocks.get(0).getLocations().length;
while (replicaCount != factor) {
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
}
blocks = dfsClient.getNamenode().
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
replicaCount = blocks.get(0).getLocations().length;
}
assertTrue(blocks.get(0).isCorrupt());
// Check if fsck reports the same
outStr = runFsck(conf, 1, true, "/");
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
assertTrue(outStr.contains("testCorruptBlock"));
}
@Test
public void testUnderMinReplicatedBlock() throws Exception {
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
// Set short retry timeouts so this test runs faster
conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10);
// Set minReplication to 2
short minReplication=2;
conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, minReplication);
FileSystem fs = null;
DFSClient dfsClient = null;
LocatedBlocks blocks = null;
int replicaCount = 0;
Random random = new Random();
String outStr = null;
short factor = 1;
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
cluster.waitActive();
fs = cluster.getFileSystem();
Path file1 = new Path("/testUnderMinReplicatedBlock");
DFSTestUtil.createFile(fs, file1, 1024, minReplication, 0);
// Wait until file replication has completed
DFSTestUtil.waitReplication(fs, file1, minReplication);
ExtendedBlock block = DFSTestUtil.getFirstBlock(fs, file1);
// Make sure filesystem is in healthy state
outStr = runFsck(conf, 0, true, "/");
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// corrupt the first replica
File blockFile = cluster.getBlockFile(0, block);
if (blockFile != null && blockFile.exists()) {
RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
FileChannel channel = raFile.getChannel();
String badString = "BADBAD";
int rand = random.nextInt((int) channel.size()/2);
raFile.seek(rand);
raFile.write(badString.getBytes());
raFile.close();
}
dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
blocks = dfsClient.getNamenode().
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
replicaCount = blocks.get(0).getLocations().length;
while (replicaCount != factor) {
try {
Thread.sleep(100);
// Read the file to trigger reportBadBlocks
try {
IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(),
conf, true);
} catch (IOException ie) {
assertTrue(ie instanceof ChecksumException);
}
System.out.println("sleep in try: replicaCount=" + replicaCount
+ " factor=" + factor);
} catch (InterruptedException ignore) {
}
blocks = dfsClient.getNamenode().
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
replicaCount = blocks.get(0).getLocations().length;
}
// Check if fsck reports the same
outStr = runFsck(conf, 0, true, "/");
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertTrue(outStr.contains("UNDER MIN REPL'D BLOCKS:\t1 (100.0 %)"));
assertTrue(outStr.contains("dfs.namenode.replication.min:\t2"));
}
@Test(timeout = 60000)
public void testFsckReplicaDetails() throws Exception {
final short replFactor = 1;
short numDn = 1;
final long blockSize = 512;
final long fileSize = 1024;
boolean checkDecommissionInProgress = false;
String[] racks = {"/rack1"};
String[] hosts = {"host1"};
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
DistributedFileSystem dfs;
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
.racks(racks).build();
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
// create files
final String testFile = new String("/testfile");
final Path path = new Path(testFile);
DFSTestUtil.createFile(dfs, path, fileSize, replFactor, 1000L);
DFSTestUtil.waitReplication(dfs, path, replFactor);
// make sure datanode that has replica is fine before decommission
String fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks",
"-replicaDetails");
assertTrue(fsckOut.contains(NamenodeFsck.HEALTHY_STATUS));
assertTrue(fsckOut.contains("(LIVE)"));
// decommission datanode
ExtendedBlock eb = DFSTestUtil.getFirstBlock(dfs, path);
FSNamesystem fsn = cluster.getNameNode().getNamesystem();
BlockManager bm = fsn.getBlockManager();
BlockCollection bc = null;
try {
fsn.writeLock();
BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
bc = fsn.getBlockCollection(bi);
} finally {
fsn.writeUnlock();
}
DatanodeDescriptor dn = bc.getBlocks()[0]
.getDatanode(0);
bm.getDatanodeManager().getDecomManager().startDecommission(dn);
String dnName = dn.getXferAddr();
// check the replica status while decommissioning
fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks",
"-replicaDetails");
assertTrue(fsckOut.contains("(DECOMMISSIONING)"));
// Start 2nd Datanode and wait for decommission to start
cluster.startDataNodes(conf, 1, true, null, null, null);
DatanodeInfo datanodeInfo = null;
do {
Thread.sleep(2000);
for (DatanodeInfo info : dfs.getDataNodeStats()) {
if (dnName.equals(info.getXferAddr())) {
datanodeInfo = info;
}
}
if (!checkDecommissionInProgress && datanodeInfo != null
&& datanodeInfo.isDecommissionInProgress()) {
checkDecommissionInProgress = true;
}
} while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
// check the replica status after decommission is done
fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks",
"-replicaDetails");
assertTrue(fsckOut.contains("(DECOMMISSIONED)"));
}
/** Test if fsck can return -1 in case of failure.
*
* @throws Exception
*/
@Test
public void testFsckError() throws Exception {
// bring up a one-node cluster
cluster = new MiniDFSCluster.Builder(conf).build();
String fileName = "/test.txt";
Path filePath = new Path(fileName);
FileSystem fs = cluster.getFileSystem();
// create a one-block file
DFSTestUtil.createFile(fs, filePath, 1L, (short)1, 1L);
DFSTestUtil.waitReplication(fs, filePath, (short)1);
// intentionally corrupt NN data structure
INodeFile node = (INodeFile) cluster.getNamesystem().dir.getINode(
fileName, true);
final BlockInfo[] blocks = node.getBlocks();
assertEquals(blocks.length, 1);
blocks[0].setNumBytes(-1L); // set the block length to be negative
// run fsck and expect a failure with -1 as the error code
String outStr = runFsck(conf, -1, true, fileName);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.FAILURE_STATUS));
// clean up file system
fs.delete(filePath, true);
}
/** check if option -list-corruptfiles of fsck command works properly. */
@Test
public void testFsckListCorruptFilesBlocks() throws Exception {
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
FileSystem fs = null;
cluster = new MiniDFSCluster.Builder(conf).build();
cluster.waitActive();
fs = cluster.getFileSystem();
DFSTestUtil util = new DFSTestUtil.Builder().
setName("testGetCorruptFiles").setNumFiles(3).setMaxLevels(1).
setMaxSize(1024).build();
util.createFiles(fs, "/corruptData", (short) 1);
util.waitReplication(fs, "/corruptData", (short) 1);
String outStr = runFsck(conf, 0, false, "/corruptData",
"-list-corruptfileblocks");
System.out.println("1. good fsck out: " + outStr);
assertTrue(outStr.contains("has 0 CORRUPT files"));
// delete the blocks
final String bpid = cluster.getNamesystem().getBlockPoolId();
for (int i=0; i<4; i++) {
for (int j=0; j<=1; j++) {
File storageDir = cluster.getInstanceStorageDir(i, j);
File dataDir = MiniDFSCluster.getFinalizedDir(storageDir, bpid);
List<File> metadataFiles = MiniDFSCluster.getAllBlockMetadataFiles(
dataDir);
if (metadataFiles == null) {
continue;
}
for (File metadataFile : metadataFiles) {
File blockFile = Block.metaToBlockFile(metadataFile);
assertTrue("Cannot remove file.", blockFile.delete());
assertTrue("Cannot remove file.", metadataFile.delete());
}
}
}
// wait for the namenode to see the corruption
final NamenodeProtocols namenode = cluster.getNameNodeRpc();
CorruptFileBlocks corruptFileBlocks = namenode
.listCorruptFileBlocks("/corruptData", null);
int numCorrupt = corruptFileBlocks.getFiles().length;
while (numCorrupt == 0) {
Thread.sleep(1000);
corruptFileBlocks = namenode
.listCorruptFileBlocks("/corruptData", null);
numCorrupt = corruptFileBlocks.getFiles().length;
}
outStr = runFsck(conf, -1, true, "/corruptData", "-list-corruptfileblocks");
System.out.println("2. bad fsck out: " + outStr);
assertTrue(outStr.contains("has 3 CORRUPT files"));
// Do a listing on a dir which doesn't have any corrupt blocks and validate
util.createFiles(fs, "/goodData");
outStr = runFsck(conf, 0, true, "/goodData", "-list-corruptfileblocks");
System.out.println("3. good fsck out: " + outStr);
assertTrue(outStr.contains("has 0 CORRUPT files"));
util.cleanup(fs, "/corruptData");
util.cleanup(fs, "/goodData");
}
/**
* Test for checking fsck command on illegal arguments should print the proper
* usage.
*/
@Test
public void testToCheckTheFsckCommandOnIllegalArguments() throws Exception {
// bring up a one-node cluster
cluster = new MiniDFSCluster.Builder(conf).build();
String fileName = "/test.txt";
Path filePath = new Path(fileName);
FileSystem fs = cluster.getFileSystem();
// create a one-block file
DFSTestUtil.createFile(fs, filePath, 1L, (short) 1, 1L);
DFSTestUtil.waitReplication(fs, filePath, (short) 1);
// passing illegal option
String outStr = runFsck(conf, -1, true, fileName, "-thisIsNotAValidFlag");
System.out.println(outStr);
assertTrue(!outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// passing multiple paths are arguments
outStr = runFsck(conf, -1, true, "/", fileName);
System.out.println(outStr);
assertTrue(!outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// clean up file system
fs.delete(filePath, true);
}
/**
* Tests that the # of missing block replicas and expected replicas is
* correct.
* @throws IOException
*/
@Test
public void testFsckMissingReplicas() throws IOException {
// Desired replication factor
// Set this higher than numReplicas so it's under-replicated
final short replFactor = 2;
// Number of replicas to actually start
final short numReplicas = 1;
// Number of blocks to write
final short numBlocks = 3;
// Set a small-ish blocksize
final long blockSize = 512;
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
DistributedFileSystem dfs = null;
// Startup a minicluster
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(numReplicas).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
// Create a file that will be intentionally under-replicated
final String pathString = new String("/testfile");
final Path path = new Path(pathString);
long fileLen = blockSize * numBlocks;
DFSTestUtil.createFile(dfs, path, fileLen, replFactor, 1);
// Create an under-replicated file
NameNode namenode = cluster.getNameNode();
NetworkTopology nettop = cluster.getNamesystem().getBlockManager()
.getDatanodeManager().getNetworkTopology();
Map<String, String[]> pmap = new HashMap<String, String[]>();
Writer result = new StringWriter();
PrintWriter out = new PrintWriter(result, true);
InetAddress remoteAddress = InetAddress.getLocalHost();
NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
numReplicas, remoteAddress);
// Run the fsck and check the Result
final HdfsFileStatus file =
namenode.getRpcServer().getFileInfo(pathString);
assertNotNull(file);
Result replRes = new ReplicationResult(conf);
Result ecRes = new ErasureCodingResult(conf);
fsck.check(pathString, file, replRes, ecRes);
// Also print the output from the fsck, for ex post facto sanity checks
System.out.println(result.toString());
assertEquals(replRes.missingReplicas,
(numBlocks*replFactor) - (numBlocks*numReplicas));
assertEquals(replRes.numExpectedReplicas, numBlocks*replFactor);
}
/**
* Tests that the # of misreplaced replicas is correct.
* @throws IOException
*/
@Test
public void testFsckMisPlacedReplicas() throws IOException {
// Desired replication factor
final short replFactor = 2;
// Number of replicas to actually start
short numDn = 2;
// Number of blocks to write
final short numBlocks = 3;
// Set a small-ish blocksize
final long blockSize = 512;
String[] racks = {"/rack1", "/rack1"};
String[] hosts = {"host1", "host2"};
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
DistributedFileSystem dfs = null;
// Startup a minicluster
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
.racks(racks).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
// Create a file that will be intentionally under-replicated
final String pathString = new String("/testfile");
final Path path = new Path(pathString);
long fileLen = blockSize * numBlocks;
DFSTestUtil.createFile(dfs, path, fileLen, replFactor, 1);
// Create an under-replicated file
NameNode namenode = cluster.getNameNode();
NetworkTopology nettop = cluster.getNamesystem().getBlockManager()
.getDatanodeManager().getNetworkTopology();
// Add a new node on different rack, so previous blocks' replicas
// are considered to be misplaced
nettop.add(DFSTestUtil.getDatanodeDescriptor("/rack2", "/host3"));
numDn++;
Map<String, String[]> pmap = new HashMap<String, String[]>();
Writer result = new StringWriter();
PrintWriter out = new PrintWriter(result, true);
InetAddress remoteAddress = InetAddress.getLocalHost();
NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
numDn, remoteAddress);
// Run the fsck and check the Result
final HdfsFileStatus file =
namenode.getRpcServer().getFileInfo(pathString);
assertNotNull(file);
Result replRes = new ReplicationResult(conf);
Result ecRes = new ErasureCodingResult(conf);
fsck.check(pathString, file, replRes, ecRes);
// check misReplicatedBlock number.
assertEquals(replRes.numMisReplicatedBlocks, numBlocks);
}
/** Test fsck with FileNotFound. */
@Test
public void testFsckFileNotFound() throws Exception {
// Number of replicas to actually start
final short numReplicas = 1;
NameNode namenode = mock(NameNode.class);
NetworkTopology nettop = mock(NetworkTopology.class);
Map<String, String[]> pmap = new HashMap<>();
Writer result = new StringWriter();
PrintWriter out = new PrintWriter(result, true);
InetAddress remoteAddress = InetAddress.getLocalHost();
FSNamesystem fsName = mock(FSNamesystem.class);
FSDirectory fsd = mock(FSDirectory.class);
BlockManager blockManager = mock(BlockManager.class);
DatanodeManager dnManager = mock(DatanodeManager.class);
INodesInPath iip = mock(INodesInPath.class);
when(namenode.getNamesystem()).thenReturn(fsName);
when(fsName.getBlockManager()).thenReturn(blockManager);
when(fsName.getFSDirectory()).thenReturn(fsd);
when(fsd.getFSNamesystem()).thenReturn(fsName);
when(fsd.resolvePath(anyObject(), anyString())).thenReturn(iip);
when(blockManager.getDatanodeManager()).thenReturn(dnManager);
NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
numReplicas, remoteAddress);
String pathString = "/tmp/testFile";
long length = 123L;
boolean isDir = false;
int blockReplication = 1;
long blockSize = 128 *1024L;
long modTime = 123123123L;
long accessTime = 123123120L;
FsPermission perms = FsPermission.getDefault();
String owner = "foo";
String group = "bar";
byte[] symlink = null;
byte[] path = DFSUtil.string2Bytes(pathString);
long fileId = 312321L;
int numChildren = 1;
byte storagePolicy = 0;
HdfsFileStatus file = new HdfsFileStatus(length, isDir, blockReplication,
blockSize, modTime, accessTime, perms, owner, group, symlink,
path, fileId, numChildren, null, storagePolicy, null);
Result replRes = new ReplicationResult(conf);
Result ecRes = new ErasureCodingResult(conf);
try {
fsck.check(pathString, file, replRes, ecRes);
} catch (Exception e) {
fail("Unexpected exception " + e.getMessage());
}
assertTrue(replRes.isHealthy());
}
/** Test fsck with symlinks in the filesystem. */
@Test
public void testFsckSymlink() throws Exception {
final DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(1).build();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
FileSystem fs = null;
final long precision = 1L;
conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY,
precision);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
fs = cluster.getFileSystem();
final String fileName = "/srcdat";
util.createFiles(fs, fileName);
final FileContext fc = FileContext.getFileContext(
cluster.getConfiguration(0));
final Path file = new Path(fileName);
final Path symlink = new Path("/srcdat-symlink");
fc.createSymlink(file, symlink, false);
util.waitReplication(fs, fileName, (short)3);
long aTime = fc.getFileStatus(symlink).getAccessTime();
Thread.sleep(precision);
setupAuditLogs();
String outStr = runFsck(conf, 0, true, "/");
verifyAuditLogs();
assertEquals(aTime, fc.getFileStatus(symlink).getAccessTime());
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertTrue(outStr.contains("Total symlinks:\t\t1"));
util.cleanup(fs, fileName);
}
/**
* Test for including the snapshot files in fsck report.
*/
@Test
public void testFsckForSnapshotFiles() throws Exception {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1)
.build();
String runFsck = runFsck(conf, 0, true, "/", "-includeSnapshots",
"-files");
assertTrue(runFsck.contains("HEALTHY"));
final String fileName = "/srcdat";
DistributedFileSystem hdfs = cluster.getFileSystem();
Path file1 = new Path(fileName);
DFSTestUtil.createFile(hdfs, file1, 1024, (short) 1, 1000L);
hdfs.allowSnapshot(new Path("/"));
hdfs.createSnapshot(new Path("/"), "mySnapShot");
runFsck = runFsck(conf, 0, true, "/", "-includeSnapshots", "-files");
assertTrue(runFsck.contains("/.snapshot/mySnapShot/srcdat"));
runFsck = runFsck(conf, 0, true, "/", "-files");
assertFalse(runFsck.contains("mySnapShot"));
}
/**
* Test for blockIdCK.
*/
@Test
public void testBlockIdCK() throws Exception {
final short replFactor = 2;
short numDn = 2;
final long blockSize = 512;
String[] racks = {"/rack1", "/rack2"};
String[] hosts = {"host1", "host2"};
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 2);
DistributedFileSystem dfs = null;
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
.racks(racks).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(1).build();
//create files
final String pathString = new String("/testfile");
final Path path = new Path(pathString);
util.createFile(dfs, path, 1024, replFactor, 1000L);
util.waitReplication(dfs, path, replFactor);
StringBuilder sb = new StringBuilder();
for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
}
String[] bIds = sb.toString().split(" ");
//run fsck
//illegal input test
String runFsckResult = runFsck(conf, 0, true, "/", "-blockId",
"not_a_block_id");
assertTrue(runFsckResult.contains("Incorrect blockId format:"));
//general test
runFsckResult = runFsck(conf, 0, true, "/", "-blockId", sb.toString());
assertTrue(runFsckResult.contains(bIds[0]));
assertTrue(runFsckResult.contains(bIds[1]));
assertTrue(runFsckResult.contains(
"Block replica on datanode/rack: host1/rack1 is HEALTHY"));
assertTrue(runFsckResult.contains(
"Block replica on datanode/rack: host2/rack2 is HEALTHY"));
}
/**
* Test for blockIdCK with datanode decommission.
*/
@Test
public void testBlockIdCKDecommission() throws Exception {
final short replFactor = 1;
short numDn = 2;
final long blockSize = 512;
boolean checkDecommissionInProgress = false;
String[] racks = {"/rack1", "/rack2"};
String[] hosts = {"host1", "host2"};
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 2);
DistributedFileSystem dfs;
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
.racks(racks).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(1).build();
//create files
final String pathString = new String("/testfile");
final Path path = new Path(pathString);
util.createFile(dfs, path, 1024, replFactor, 1000L);
util.waitReplication(dfs, path, replFactor);
StringBuilder sb = new StringBuilder();
for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
}
String[] bIds = sb.toString().split(" ");
//make sure datanode that has replica is fine before decommission
String outStr = runFsck(conf, 0, true, "/", "-blockId", bIds[0]);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
//decommission datanode
FSNamesystem fsn = cluster.getNameNode().getNamesystem();
BlockManager bm = fsn.getBlockManager();
ExtendedBlock eb = util.getFirstBlock(dfs, path);
BlockCollection bc = null;
try {
fsn.writeLock();
BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
bc = fsn.getBlockCollection(bi);
} finally {
fsn.writeUnlock();
}
DatanodeDescriptor dn = bc.getBlocks()[0].getDatanode(0);
bm.getDatanodeManager().getDecomManager().startDecommission(dn);
String dnName = dn.getXferAddr();
//wait for decommission start
DatanodeInfo datanodeInfo = null;
int count = 0;
do {
Thread.sleep(2000);
for (DatanodeInfo info : dfs.getDataNodeStats()) {
if (dnName.equals(info.getXferAddr())) {
datanodeInfo = info;
}
}
//check decommissioning only once
if(!checkDecommissionInProgress && datanodeInfo != null
&& datanodeInfo.isDecommissionInProgress()) {
String fsckOut = runFsck(conf, 3, true, "/", "-blockId", bIds[0]);
assertTrue(fsckOut.contains(NamenodeFsck.DECOMMISSIONING_STATUS));
checkDecommissionInProgress = true;
}
} while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
//check decommissioned
String fsckOut = runFsck(conf, 2, true, "/", "-blockId", bIds[0]);
assertTrue(fsckOut.contains(NamenodeFsck.DECOMMISSIONED_STATUS));
}
/**
* Test for blockIdCK with block corruption.
*/
@Test
public void testBlockIdCKCorruption() throws Exception {
short numDn = 1;
final long blockSize = 512;
Random random = new Random();
ExtendedBlock block;
short repFactor = 1;
String[] racks = {"/rack1"};
String[] hosts = {"host1"};
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
// Set short retry timeouts so this test runs faster
conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10);
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
DistributedFileSystem dfs = null;
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
.racks(racks).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(1).build();
//create files
final String pathString = new String("/testfile");
final Path path = new Path(pathString);
util.createFile(dfs, path, 1024, repFactor, 1000L);
util.waitReplication(dfs, path, repFactor);
StringBuilder sb = new StringBuilder();
for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
}
String[] bIds = sb.toString().split(" ");
//make sure block is healthy before we corrupt it
String outStr = runFsck(conf, 0, true, "/", "-blockId", bIds[0]);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// corrupt replicas
block = DFSTestUtil.getFirstBlock(dfs, path);
File blockFile = cluster.getBlockFile(0, block);
if (blockFile != null && blockFile.exists()) {
RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
FileChannel channel = raFile.getChannel();
String badString = "BADBAD";
int rand = random.nextInt((int) channel.size()/2);
raFile.seek(rand);
raFile.write(badString.getBytes());
raFile.close();
}
util.waitCorruptReplicas(dfs, cluster.getNamesystem(), path, block, 1);
outStr = runFsck(conf, 1, false, "/", "-blockId", block.getBlockName());
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
}
private void writeFile(final DistributedFileSystem dfs,
Path dir, String fileName) throws IOException {
Path filePath = new Path(dir.toString() + Path.SEPARATOR + fileName);
final FSDataOutputStream out = dfs.create(filePath);
out.writeChars("teststring");
out.close();
}
private void writeFile(final DistributedFileSystem dfs,
String dirName, String fileName, String storagePolicy)
throws IOException {
Path dirPath = new Path(dirName);
dfs.mkdirs(dirPath);
dfs.setStoragePolicy(dirPath, storagePolicy);
writeFile(dfs, dirPath, fileName);
}
/**
* Test storage policy display.
*/
@Test
public void testStoragePoliciesCK() throws Exception {
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(3)
.storageTypes(
new StorageType[] {StorageType.DISK, StorageType.ARCHIVE})
.build();
cluster.waitActive();
final DistributedFileSystem dfs = cluster.getFileSystem();
writeFile(dfs, "/testhot", "file", "HOT");
writeFile(dfs, "/testwarm", "file", "WARM");
writeFile(dfs, "/testcold", "file", "COLD");
String outStr = runFsck(conf, 0, true, "/", "-storagepolicies");
assertTrue(outStr.contains("DISK:3(HOT)"));
assertTrue(outStr.contains("DISK:1,ARCHIVE:2(WARM)"));
assertTrue(outStr.contains("ARCHIVE:3(COLD)"));
assertTrue(outStr.contains("All blocks satisfy specified storage policy."));
dfs.setStoragePolicy(new Path("/testhot"), "COLD");
dfs.setStoragePolicy(new Path("/testwarm"), "COLD");
outStr = runFsck(conf, 0, true, "/", "-storagepolicies");
assertTrue(outStr.contains("DISK:3(HOT)"));
assertTrue(outStr.contains("DISK:1,ARCHIVE:2(WARM)"));
assertTrue(outStr.contains("ARCHIVE:3(COLD)"));
assertFalse(outStr.contains(
"All blocks satisfy specified storage policy."));
}
/**
* Test for blocks on decommissioning hosts are not shown as missing.
*/
@Test
public void testFsckWithDecommissionedReplicas() throws Exception {
final short replFactor = 1;
short numDn = 2;
final long blockSize = 512;
final long fileSize = 1024;
boolean checkDecommissionInProgress = false;
String[] racks = {"/rack1", "/rack2"};
String[] hosts = {"host1", "host2"};
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
DistributedFileSystem dfs;
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
.racks(racks).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(1).build();
//create files
final String testFile = new String("/testfile");
final Path path = new Path(testFile);
util.createFile(dfs, path, fileSize, replFactor, 1000L);
util.waitReplication(dfs, path, replFactor);
// make sure datanode that has replica is fine before decommission
String outStr = runFsck(conf, 0, true, testFile);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// decommission datanode
FSNamesystem fsn = cluster.getNameNode().getNamesystem();
BlockManager bm = fsn.getBlockManager();
ExtendedBlock eb = util.getFirstBlock(dfs, path);
BlockCollection bc = null;
try {
fsn.writeLock();
BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
bc = fsn.getBlockCollection(bi);
} finally {
fsn.writeUnlock();
}
DatanodeDescriptor dn = bc.getBlocks()[0]
.getDatanode(0);
bm.getDatanodeManager().getDecomManager().startDecommission(dn);
String dnName = dn.getXferAddr();
// wait for decommission start
DatanodeInfo datanodeInfo = null;
int count = 0;
do {
Thread.sleep(2000);
for (DatanodeInfo info : dfs.getDataNodeStats()) {
if (dnName.equals(info.getXferAddr())) {
datanodeInfo = info;
}
}
// check the replica status should be healthy(0)
// instead of corruption (1) during decommissioning
if(!checkDecommissionInProgress && datanodeInfo != null
&& datanodeInfo.isDecommissionInProgress()) {
String fsckOut = runFsck(conf, 0, true, testFile);
checkDecommissionInProgress = true;
}
} while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
// check the replica status should be healthy(0) after decommission
// is done
String fsckOut = runFsck(conf, 0, true, testFile);
}
@Test
public void testECFsck() throws Exception {
FileSystem fs = null;
final long precision = 1L;
conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY,
precision);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
int dataBlocks = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getNumDataUnits();
int parityBlocks = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getNumParityUnits();
int totalSize = dataBlocks + parityBlocks;
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(totalSize).build();
fs = cluster.getFileSystem();
// create a contiguous file
Path replDirPath = new Path("/replicated");
Path replFilePath = new Path(replDirPath, "replfile");
final short factor = 3;
DFSTestUtil.createFile(fs, replFilePath, 1024, factor, 0);
DFSTestUtil.waitReplication(fs, replFilePath, factor);
// create a large striped file
Path ecDirPath = new Path("/striped");
Path largeFilePath = new Path(ecDirPath, "largeFile");
DFSTestUtil.createStripedFile(cluster, largeFilePath, ecDirPath, 1, 2,
true);
// create a small striped file
Path smallFilePath = new Path(ecDirPath, "smallFile");
DFSTestUtil.writeFile(fs, smallFilePath, "hello world!");
long replTime = fs.getFileStatus(replFilePath).getAccessTime();
long ecTime = fs.getFileStatus(largeFilePath).getAccessTime();
Thread.sleep(precision);
setupAuditLogs();
String outStr = runFsck(conf, 0, true, "/");
verifyAuditLogs();
assertEquals(replTime, fs.getFileStatus(replFilePath).getAccessTime());
assertEquals(ecTime, fs.getFileStatus(largeFilePath).getAccessTime());
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
shutdownCluster();
// restart the cluster; bring up namenode but not the data nodes
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0).format(false).build();
outStr = runFsck(conf, 1, true, "/");
// expect the result is corrupt
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
System.out.println(outStr);
}
/**
* Test that corrupted snapshot files are listed with full dir.
*/
@Test
public void testFsckListCorruptSnapshotFiles() throws Exception {
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
DistributedFileSystem hdfs = null;
final short replFactor = 1;
int numFiles = 3;
int numSnapshots = 0;
cluster = new MiniDFSCluster.Builder(conf).build();
cluster.waitActive();
hdfs = cluster.getFileSystem();
DFSTestUtil util = new DFSTestUtil.Builder().
setName("testGetCorruptFiles").setNumFiles(numFiles).setMaxLevels(1).
setMaxSize(1024).build();
util.createFiles(hdfs, "/corruptData", (short) 1);
final Path fp = new Path("/corruptData/file");
util.createFile(hdfs, fp, 1024, replFactor, 1000L);
numFiles++;
util.waitReplication(hdfs, "/corruptData", (short) 1);
hdfs.allowSnapshot(new Path("/corruptData"));
hdfs.createSnapshot(new Path("/corruptData"), "mySnapShot");
numSnapshots = numFiles;
String outStr =
runFsck(conf, 0, false, "/corruptData", "-list-corruptfileblocks");
System.out.println("1. good fsck out: " + outStr);
assertTrue(outStr.contains("has 0 CORRUPT files"));
// delete the blocks
final String bpid = cluster.getNamesystem().getBlockPoolId();
for (int i=0; i<numFiles; i++) {
for (int j=0; j<=1; j++) {
File storageDir = cluster.getInstanceStorageDir(i, j);
File dataDir = MiniDFSCluster.getFinalizedDir(storageDir, bpid);
List<File> metadataFiles = MiniDFSCluster.getAllBlockMetadataFiles(
dataDir);
if (metadataFiles == null) {
continue;
}
for (File metadataFile : metadataFiles) {
File blockFile = Block.metaToBlockFile(metadataFile);
assertTrue("Cannot remove file.", blockFile.delete());
assertTrue("Cannot remove file.", metadataFile.delete());
}
}
}
// Delete file when it has a snapshot
hdfs.delete(fp, false);
numFiles--;
// wait for the namenode to see the corruption
final NamenodeProtocols namenode = cluster.getNameNodeRpc();
CorruptFileBlocks corruptFileBlocks = namenode
.listCorruptFileBlocks("/corruptData", null);
int numCorrupt = corruptFileBlocks.getFiles().length;
while (numCorrupt == 0) {
Thread.sleep(1000);
corruptFileBlocks = namenode
.listCorruptFileBlocks("/corruptData", null);
numCorrupt = corruptFileBlocks.getFiles().length;
}
// with -includeSnapshots all files are reported
outStr = runFsck(conf, -1, true, "/corruptData",
"-list-corruptfileblocks", "-includeSnapshots");
System.out.println("2. bad fsck include snapshot out: " + outStr);
assertTrue(outStr
.contains("has " + (numFiles + numSnapshots) + " CORRUPT files"));
assertTrue(outStr.contains("/.snapshot/"));
// without -includeSnapshots only non-snapshots are reported
outStr =
runFsck(conf, -1, true, "/corruptData", "-list-corruptfileblocks");
System.out.println("3. bad fsck exclude snapshot out: " + outStr);
assertTrue(outStr.contains("has " + numFiles + " CORRUPT files"));
assertFalse(outStr.contains("/.snapshot/"));
}
@Test (timeout = 300000)
public void testFsckMoveAfterCorruption() throws Exception {
final int dfsBlockSize = 512 * 1024;
final int numDatanodes = 1;
final int replication = 1;
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, dfsBlockSize);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000L);
conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, replication);
cluster = new MiniDFSCluster.Builder(conf).build();
DistributedFileSystem dfs = cluster.getFileSystem();
cluster.waitActive();
final String srcDir = "/srcdat";
final DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck")
.setMinSize(dfsBlockSize * 2).setMaxSize(dfsBlockSize * 3)
.setNumFiles(1).build();
util.createFiles(dfs, srcDir, (short) replication);
final String[] fileNames = util.getFileNames(srcDir);
LOG.info("Created files: " + Arrays.toString(fileNames));
// Run fsck here. The output is automatically logged for easier debugging
String outStr = runFsck(conf, 0, true, "/", "-files", "-blocks");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// Corrupt the first block
final DFSClient dfsClient = new DFSClient(
new InetSocketAddress("localhost", cluster.getNameNodePort()), conf);
final String blockFileToCorrupt = fileNames[0];
final CorruptedTestFile ctf = new CorruptedTestFile(blockFileToCorrupt,
Sets.newHashSet(0), dfsClient, numDatanodes, dfsBlockSize);
ctf.corruptBlocks(cluster);
// Wait for fsck to discover all the missing blocks
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
try {
final String str = runFsck(conf, 1, false, "/");
String numCorrupt = null;
for (String line : str.split(LINE_SEPARATOR)) {
Matcher m = NUM_CORRUPT_BLOCKS_PATTERN.matcher(line);
if (m.matches()) {
numCorrupt = m.group(1);
break;
}
}
if (numCorrupt == null) {
Assert.fail("Cannot find corrupt blocks count in fsck output.");
}
if (Integer.parseInt(numCorrupt) == ctf.getTotalMissingBlocks()) {
assertTrue(str.contains(NamenodeFsck.CORRUPT_STATUS));
return true;
}
} catch (Exception e) {
LOG.error("Exception caught", e);
Assert.fail("Caught unexpected exception.");
}
return false;
}
}, 1000, 60000);
runFsck(conf, 1, true, "/", "-files", "-blocks", "-racks");
LOG.info("Moving blocks to lost+found");
// Fsck will return error since we corrupted a block
runFsck(conf, 1, false, "/", "-move");
final List<LocatedFileStatus> retVal = new ArrayList<>();
final RemoteIterator<LocatedFileStatus> iter =
dfs.listFiles(new Path("/lost+found"), true);
while (iter.hasNext()) {
retVal.add(iter.next());
}
LOG.info("Items in lost+found: " + retVal);
// Expect all good blocks moved, only corrupted block skipped.
long totalLength = 0;
for (LocatedFileStatus lfs: retVal) {
totalLength += lfs.getLen();
}
Assert.assertTrue("Nothing is moved to lost+found!", totalLength > 0);
util.cleanup(dfs, srcDir);
}
@Test(timeout = 60000)
public void testFsckUpgradeDomain() throws Exception {
testUpgradeDomain(false, false);
testUpgradeDomain(false, true);
testUpgradeDomain(true, false);
testUpgradeDomain(true, true);
}
private void testUpgradeDomain(boolean defineUpgradeDomain,
boolean displayUpgradeDomain) throws Exception {
final short replFactor = 1;
final short numDN = 1;
final long blockSize = 512;
final long fileSize = 1024;
final String upgradeDomain = "ud1";
final String[] racks = {"/rack1"};
final String[] hosts = {"127.0.0.1"};
HostsFileWriter hostsFileWriter = new HostsFileWriter();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, replFactor);
if (defineUpgradeDomain) {
conf.setClass(DFSConfigKeys.DFS_NAMENODE_HOSTS_PROVIDER_CLASSNAME_KEY,
CombinedHostFileManager.class, HostConfigManager.class);
hostsFileWriter.initialize(conf, "temp/fsckupgradedomain");
}
DistributedFileSystem dfs;
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDN).
hosts(hosts).racks(racks).build();
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
// Configure the upgrade domain on the datanode
if (defineUpgradeDomain) {
DatanodeAdminProperties dnProp = new DatanodeAdminProperties();
DatanodeID datanodeID = cluster.getDataNodes().get(0).getDatanodeId();
dnProp.setHostName(datanodeID.getHostName());
dnProp.setPort(datanodeID.getXferPort());
dnProp.setUpgradeDomain(upgradeDomain);
hostsFileWriter.initIncludeHosts(new DatanodeAdminProperties[]{dnProp});
cluster.getFileSystem().refreshNodes();
}
// create files
final String testFile = new String("/testfile");
final Path path = new Path(testFile);
DFSTestUtil.createFile(dfs, path, fileSize, replFactor, 1000L);
DFSTestUtil.waitReplication(dfs, path, replFactor);
try {
String fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks",
displayUpgradeDomain ? "-upgradedomains" : "-locations");
assertTrue(fsckOut.contains(NamenodeFsck.HEALTHY_STATUS));
String udValue = defineUpgradeDomain ? upgradeDomain :
NamenodeFsck.UNDEFINED;
assertEquals(displayUpgradeDomain,
fsckOut.contains("(ud=" + udValue + ")"));
} finally {
if (defineUpgradeDomain) {
hostsFileWriter.cleanup();
}
}
}
@Test (timeout = 300000)
public void testFsckCorruptECFile() throws Exception {
DistributedFileSystem fs = null;
int dataBlocks = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getNumDataUnits();
int parityBlocks = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getNumParityUnits();
int cellSize = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getCellSize();
int totalSize = dataBlocks + parityBlocks;
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(totalSize).build();
fs = cluster.getFileSystem();
Map<Integer, Integer> dnIndices = new HashMap<>();
ArrayList<DataNode> dnList = cluster.getDataNodes();
for (int i = 0; i < totalSize; i++) {
dnIndices.put(dnList.get(i).getIpcPort(), i);
}
// create file
Path ecDirPath = new Path("/striped");
fs.mkdir(ecDirPath, FsPermission.getDirDefault());
fs.getClient().setErasureCodingPolicy(ecDirPath.toString(), null);
Path file = new Path(ecDirPath, "corrupted");
final int length = cellSize * dataBlocks;
final byte[] bytes = StripedFileTestUtil.generateBytes(length);
DFSTestUtil.writeFile(fs, file, bytes);
LocatedStripedBlock lsb = (LocatedStripedBlock)fs.getClient()
.getLocatedBlocks(file.toString(), 0, cellSize * dataBlocks).get(0);
final LocatedBlock[] blks = StripedBlockUtil.parseStripedBlockGroup(lsb,
cellSize, dataBlocks, parityBlocks);
// make an unrecoverable ec file with corrupted blocks
for(int i = 0; i < parityBlocks + 1; i++) {
int ipcPort = blks[i].getLocations()[0].getIpcPort();
int dnIndex = dnIndices.get(ipcPort);
File storageDir = cluster.getInstanceStorageDir(dnIndex, 0);
File blkFile = MiniDFSCluster.getBlockFile(storageDir,
blks[i].getBlock());
Assert.assertTrue("Block file does not exist", blkFile.exists());
FileOutputStream out = new FileOutputStream(blkFile);
out.write("corruption".getBytes());
}
// disable the heart beat from DN so that the corrupted block record is
// kept in NameNode
for (DataNode dn : cluster.getDataNodes()) {
DataNodeTestUtils.setHeartbeatsDisabledForTests(dn, true);
}
// Read the file to trigger reportBadBlocks
try {
IOUtils.copyBytes(fs.open(file), new IOUtils.NullOutputStream(), conf,
true);
} catch (IOException ie) {
assertTrue(ie.getMessage().contains(
"missingChunksNum=" + (parityBlocks + 1)));
}
waitForUnrecoverableBlockGroup(conf);
String outStr = runFsck(conf, 1, true, "/");
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
}
@Test (timeout = 300000)
public void testFsckMissingECFile() throws Exception {
DistributedFileSystem fs = null;
int dataBlocks = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getNumDataUnits();
int parityBlocks = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getNumParityUnits();
int cellSize = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getCellSize();
int totalSize = dataBlocks + parityBlocks;
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(totalSize).build();
fs = cluster.getFileSystem();
// create file
Path ecDirPath = new Path("/striped");
fs.mkdir(ecDirPath, FsPermission.getDirDefault());
fs.getClient().setErasureCodingPolicy(ecDirPath.toString(), null);
Path file = new Path(ecDirPath, "missing");
final int length = cellSize * dataBlocks;
final byte[] bytes = StripedFileTestUtil.generateBytes(length);
DFSTestUtil.writeFile(fs, file, bytes);
// make an unrecoverable ec file with missing blocks
ArrayList<DataNode> dns = cluster.getDataNodes();
DatanodeID dnId;
for (int i = 0; i < parityBlocks + 1; i++) {
dnId = dns.get(i).getDatanodeId();
cluster.stopDataNode(dnId.getXferAddr());
cluster.setDataNodeDead(dnId);
}
waitForUnrecoverableBlockGroup(conf);
String outStr = runFsck(conf, 1, true, "/", "-files", "-blocks",
"-locations");
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
assertTrue(outStr.contains("Live_repl=" + (dataBlocks - 1)));
}
private void waitForUnrecoverableBlockGroup(Configuration configuration)
throws TimeoutException, InterruptedException {
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
try {
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bStream, true);
ToolRunner.run(new DFSck(configuration, out), new String[] {"/"});
String outStr = bStream.toString();
if (outStr.contains("UNRECOVERABLE BLOCK GROUPS")) {
return true;
}
} catch (Exception e) {
LOG.error("Exception caught", e);
Assert.fail("Caught unexpected exception.");
}
return false;
}
}, 1000, 60000);
}
}
| hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFsck.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Supplier;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.UnresolvedLinkException;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSInputStream;
import org.apache.hadoop.hdfs.DFSOutputStream;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdfs.StripedFileTestUtil;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks;
import org.apache.hadoop.hdfs.protocol.DatanodeAdminProperties;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.LocatedStripedBlock;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockCollection;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
import org.apache.hadoop.hdfs.server.blockmanagement.CombinedHostFileManager;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager;
import org.apache.hadoop.hdfs.server.blockmanagement.HostConfigManager;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
import org.apache.hadoop.hdfs.server.namenode.NamenodeFsck.Result;
import org.apache.hadoop.hdfs.server.namenode.NamenodeFsck.ReplicationResult;
import org.apache.hadoop.hdfs.server.namenode.NamenodeFsck.ErasureCodingResult;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.hdfs.tools.DFSck;
import org.apache.hadoop.hdfs.util.HostsFileWriter;
import org.apache.hadoop.hdfs.util.StripedBlockUtil;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.net.NetworkTopology;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.Sets;
/**
* A JUnit test for doing fsck
*/
public class TestFsck {
static final String AUDITLOG_FILE =
GenericTestUtils.getTempPath("TestFsck-audit.log");
// Pattern for:
// allowed=true ugi=name ip=/address cmd=FSCK src=/ dst=null perm=null
static final Pattern fsckPattern = Pattern.compile(
"allowed=.*?\\s" +
"ugi=.*?\\s" +
"ip=/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\s" +
"cmd=fsck\\ssrc=\\/\\sdst=null\\s" +
"perm=null\\s" + "proto=.*");
static final Pattern getfileinfoPattern = Pattern.compile(
"allowed=.*?\\s" +
"ugi=.*?\\s" +
"ip=/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\s" +
"cmd=getfileinfo\\ssrc=\\/\\sdst=null\\s" +
"perm=null\\s" + "proto=.*");
static final Pattern numMissingBlocksPattern = Pattern.compile(
".*Missing blocks:\t\t([0123456789]*).*");
static final Pattern numCorruptBlocksPattern = Pattern.compile(
".*Corrupt blocks:\t\t([0123456789]*).*");
private static final String LINE_SEPARATOR =
System.getProperty("line.separator");
static String runFsck(Configuration conf, int expectedErrCode,
boolean checkErrorCode,String... path)
throws Exception {
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bStream, true);
GenericTestUtils.setLogLevel(FSPermissionChecker.LOG, Level.ALL);
int errCode = ToolRunner.run(new DFSck(conf, out), path);
if (checkErrorCode) {
assertEquals(expectedErrCode, errCode);
}
GenericTestUtils.setLogLevel(FSPermissionChecker.LOG, Level.INFO);
FSImage.LOG.info("OUTPUT = " + bStream.toString());
return bStream.toString();
}
/** do fsck */
@Test
public void testFsck() throws Exception {
DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck").
setNumFiles(20).build();
MiniDFSCluster cluster = null;
FileSystem fs = null;
try {
Configuration conf = new HdfsConfiguration();
final long precision = 1L;
conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, precision);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
fs = cluster.getFileSystem();
final String fileName = "/srcdat";
util.createFiles(fs, fileName);
util.waitReplication(fs, fileName, (short)3);
final Path file = new Path(fileName);
long aTime = fs.getFileStatus(file).getAccessTime();
Thread.sleep(precision);
setupAuditLogs();
String outStr = runFsck(conf, 0, true, "/");
verifyAuditLogs();
assertEquals(aTime, fs.getFileStatus(file).getAccessTime());
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
if (fs != null) {try{fs.close();} catch(Exception e){}}
cluster.shutdown();
// restart the cluster; bring up namenode but not the data nodes
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0).format(false).build();
outStr = runFsck(conf, 1, true, "/");
// expect the result is corrupt
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
System.out.println(outStr);
// bring up data nodes & cleanup cluster
cluster.startDataNodes(conf, 4, true, null, null);
cluster.waitActive();
cluster.waitClusterUp();
fs = cluster.getFileSystem();
util.cleanup(fs, "/srcdat");
} finally {
if (fs != null) {try{fs.close();} catch(Exception e){}}
if (cluster != null) { cluster.shutdown(); }
}
}
/** Sets up log4j logger for auditlogs */
private void setupAuditLogs() throws IOException {
File file = new File(AUDITLOG_FILE);
if (file.exists()) {
file.delete();
}
Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
logger.setLevel(Level.INFO);
PatternLayout layout = new PatternLayout("%m%n");
RollingFileAppender appender =
new RollingFileAppender(layout, AUDITLOG_FILE);
logger.addAppender(appender);
}
private void verifyAuditLogs() throws IOException {
// Turn off the logs
Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
logger.setLevel(Level.OFF);
BufferedReader reader = null;
try {
// Audit log should contain one getfileinfo and one fsck
reader = new BufferedReader(new FileReader(AUDITLOG_FILE));
String line;
// one extra getfileinfo stems from resolving the path
//
for (int i = 0; i < 2; i++) {
line = reader.readLine();
assertNotNull(line);
assertTrue("Expected getfileinfo event not found in audit log",
getfileinfoPattern.matcher(line).matches());
}
line = reader.readLine();
assertNotNull(line);
assertTrue("Expected fsck event not found in audit log", fsckPattern
.matcher(line).matches());
assertNull("Unexpected event in audit log", reader.readLine());
} finally {
// Close the reader and remove the appender to release the audit log file
// handle after verifying the content of the file.
if (reader != null) {
reader.close();
}
if (logger != null) {
logger.removeAllAppenders();
}
}
}
@Test
public void testFsckNonExistent() throws Exception {
DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck").
setNumFiles(20).build();
MiniDFSCluster cluster = null;
FileSystem fs = null;
try {
Configuration conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
fs = cluster.getFileSystem();
util.createFiles(fs, "/srcdat");
util.waitReplication(fs, "/srcdat", (short)3);
String outStr = runFsck(conf, 0, true, "/non-existent");
assertEquals(-1, outStr.indexOf(NamenodeFsck.HEALTHY_STATUS));
System.out.println(outStr);
util.cleanup(fs, "/srcdat");
} finally {
if (fs != null) {try{fs.close();} catch(Exception e){}}
if (cluster != null) { cluster.shutdown(); }
}
}
/** Test fsck with permission set on inodes */
@Test
public void testFsckPermission() throws Exception {
final DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(20).build();
final Configuration conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
MiniDFSCluster cluster = null;
try {
// Create a cluster with the current user, write some files
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
final MiniDFSCluster c2 = cluster;
final String dir = "/dfsck";
final Path dirpath = new Path(dir);
final FileSystem fs = c2.getFileSystem();
util.createFiles(fs, dir);
util.waitReplication(fs, dir, (short) 3);
fs.setPermission(dirpath, new FsPermission((short) 0700));
// run DFSck as another user, should fail with permission issue
UserGroupInformation fakeUGI = UserGroupInformation.createUserForTesting(
"ProbablyNotARealUserName", new String[] { "ShangriLa" });
fakeUGI.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
System.out.println(runFsck(conf, -1, true, dir));
return null;
}
});
// set permission and try DFSck again as the fake user, should succeed
fs.setPermission(dirpath, new FsPermission((short) 0777));
fakeUGI.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final String outStr = runFsck(conf, 0, true, dir);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
return null;
}
});
util.cleanup(fs, dir);
} finally {
if (cluster != null) { cluster.shutdown(); }
}
}
@Test
public void testFsckMove() throws Exception {
Configuration conf = new HdfsConfiguration();
final int DFS_BLOCK_SIZE = 1024;
final int NUM_DATANODES = 4;
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DFS_BLOCK_SIZE);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
DFSTestUtil util = new DFSTestUtil("TestFsck", 5, 3,
(5 * DFS_BLOCK_SIZE) + (DFS_BLOCK_SIZE - 1), 5 * DFS_BLOCK_SIZE);
MiniDFSCluster cluster = null;
FileSystem fs = null;
try {
cluster = new MiniDFSCluster.Builder(conf).
numDataNodes(NUM_DATANODES).build();
String topDir = "/srcdat";
fs = cluster.getFileSystem();
cluster.waitActive();
util.createFiles(fs, topDir);
util.waitReplication(fs, topDir, (short)3);
String outStr = runFsck(conf, 0, true, "/");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
DFSClient dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
String fileNames[] = util.getFileNames(topDir);
CorruptedTestFile ctFiles[] = new CorruptedTestFile[] {
new CorruptedTestFile(fileNames[0], Sets.newHashSet(0),
dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE),
new CorruptedTestFile(fileNames[1], Sets.newHashSet(2, 3),
dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE),
new CorruptedTestFile(fileNames[2], Sets.newHashSet(4),
dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE),
new CorruptedTestFile(fileNames[3], Sets.newHashSet(0, 1, 2, 3),
dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE),
new CorruptedTestFile(fileNames[4], Sets.newHashSet(1, 2, 3, 4),
dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE)
};
int totalMissingBlocks = 0;
for (CorruptedTestFile ctFile : ctFiles) {
totalMissingBlocks += ctFile.getTotalMissingBlocks();
}
for (CorruptedTestFile ctFile : ctFiles) {
ctFile.removeBlocks(cluster);
}
// Wait for fsck to discover all the missing blocks
while (true) {
outStr = runFsck(conf, 1, false, "/");
String numMissing = null;
String numCorrupt = null;
for (String line : outStr.split(LINE_SEPARATOR)) {
Matcher m = numMissingBlocksPattern.matcher(line);
if (m.matches()) {
numMissing = m.group(1);
}
m = numCorruptBlocksPattern.matcher(line);
if (m.matches()) {
numCorrupt = m.group(1);
}
if (numMissing != null && numCorrupt != null) {
break;
}
}
if (numMissing == null || numCorrupt == null) {
throw new IOException("failed to find number of missing or corrupt" +
" blocks in fsck output.");
}
if (numMissing.equals(Integer.toString(totalMissingBlocks))) {
assertTrue(numCorrupt.equals(Integer.toString(0)));
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
}
}
// Copy the non-corrupt blocks of corruptFileName to lost+found.
outStr = runFsck(conf, 1, false, "/", "-move");
FSImage.LOG.info("WATERMELON: outStr = " + outStr);
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
// Make sure that we properly copied the block files from the DataNodes
// to lost+found
for (CorruptedTestFile ctFile : ctFiles) {
ctFile.checkSalvagedRemains();
}
// Fix the filesystem by removing corruptFileName
outStr = runFsck(conf, 1, true, "/", "-delete");
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
// Check to make sure we have a healthy filesystem
outStr = runFsck(conf, 0, true, "/");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
util.cleanup(fs, topDir);
} finally {
if (fs != null) {try{fs.close();} catch(Exception e){}}
if (cluster != null) { cluster.shutdown(); }
}
}
static private class CorruptedTestFile {
final private String name;
final private Set<Integer> blocksToCorrupt;
final private DFSClient dfsClient;
final private int numDataNodes;
final private int blockSize;
final private byte[] initialContents;
public CorruptedTestFile(String name, Set<Integer> blocksToCorrupt,
DFSClient dfsClient, int numDataNodes, int blockSize)
throws IOException {
this.name = name;
this.blocksToCorrupt = blocksToCorrupt;
this.dfsClient = dfsClient;
this.numDataNodes = numDataNodes;
this.blockSize = blockSize;
this.initialContents = cacheInitialContents();
}
public int getTotalMissingBlocks() {
return blocksToCorrupt.size();
}
private byte[] cacheInitialContents() throws IOException {
HdfsFileStatus status = dfsClient.getFileInfo(name);
byte[] content = new byte[(int)status.getLen()];
DFSInputStream in = null;
try {
in = dfsClient.open(name);
IOUtils.readFully(in, content, 0, content.length);
} finally {
in.close();
}
return content;
}
public void removeBlocks(MiniDFSCluster cluster)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
for (int corruptIdx : blocksToCorrupt) {
// Corrupt a block by deleting it
ExtendedBlock block = dfsClient.getNamenode().getBlockLocations(
name, blockSize * corruptIdx, Long.MAX_VALUE).get(0).getBlock();
for (int i = 0; i < numDataNodes; i++) {
File blockFile = cluster.getBlockFile(i, block);
if(blockFile != null && blockFile.exists()) {
assertTrue(blockFile.delete());
}
}
}
}
public void corruptBlocks(MiniDFSCluster cluster) throws IOException {
for (int corruptIdx : blocksToCorrupt) {
// Corrupt a block by deleting it
ExtendedBlock block = dfsClient.getNamenode().getBlockLocations(name,
blockSize * corruptIdx, Long.MAX_VALUE).get(0).getBlock();
for (int i = 0; i < numDataNodes; i++) {
File blockFile = cluster.getBlockFile(i, block);
if(blockFile != null && blockFile.exists()) {
FileOutputStream blockFileStream =
new FileOutputStream(blockFile, false);
blockFileStream.write("corrupt".getBytes());
blockFileStream.close();
FSImage.LOG.info("Corrupted block file " + blockFile);
}
}
}
}
public void checkSalvagedRemains() throws IOException {
int chainIdx = 0;
HdfsFileStatus status = dfsClient.getFileInfo(name);
long length = status.getLen();
int numBlocks = (int)((length + blockSize - 1) / blockSize);
DFSInputStream in = null;
byte[] blockBuffer = new byte[blockSize];
try {
for (int blockIdx = 0; blockIdx < numBlocks; blockIdx++) {
if (blocksToCorrupt.contains(blockIdx)) {
if (in != null) {
in.close();
in = null;
}
continue;
}
if (in == null) {
in = dfsClient.open("/lost+found" + name + "/" + chainIdx);
chainIdx++;
}
int len = blockBuffer.length;
if (blockIdx == (numBlocks - 1)) {
// The last block might not be full-length
len = (int)(in.getFileLength() % blockSize);
if (len == 0) len = blockBuffer.length;
}
IOUtils.readFully(in, blockBuffer, 0, len);
int startIdx = blockIdx * blockSize;
for (int i = 0; i < len; i++) {
if (initialContents[startIdx + i] != blockBuffer[i]) {
throw new IOException("salvaged file " + name + " differed " +
"from what we expected on block " + blockIdx);
}
}
}
} finally {
IOUtils.cleanup(null, in);
}
}
}
@Test
public void testFsckMoveAndDelete() throws Exception {
final int MAX_MOVE_TRIES = 5;
DFSTestUtil util = new DFSTestUtil.Builder().
setName("TestFsckMoveAndDelete").setNumFiles(5).build();
MiniDFSCluster cluster = null;
FileSystem fs = null;
try {
Configuration conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
String topDir = "/srcdat";
fs = cluster.getFileSystem();
cluster.waitActive();
util.createFiles(fs, topDir);
util.waitReplication(fs, topDir, (short)3);
String outStr = runFsck(conf, 0, true, "/");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// Corrupt a block by deleting it
String[] fileNames = util.getFileNames(topDir);
DFSClient dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
String corruptFileName = fileNames[0];
ExtendedBlock block = dfsClient.getNamenode().getBlockLocations(
corruptFileName, 0, Long.MAX_VALUE).get(0).getBlock();
for (int i=0; i<4; i++) {
File blockFile = cluster.getBlockFile(i, block);
if(blockFile != null && blockFile.exists()) {
assertTrue(blockFile.delete());
}
}
// We excpect the filesystem to be corrupted
outStr = runFsck(conf, 1, false, "/");
while (!outStr.contains(NamenodeFsck.CORRUPT_STATUS)) {
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
}
outStr = runFsck(conf, 1, false, "/");
}
// After a fsck -move, the corrupted file should still exist.
for (int i = 0; i < MAX_MOVE_TRIES; i++) {
outStr = runFsck(conf, 1, true, "/", "-move" );
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
String[] newFileNames = util.getFileNames(topDir);
boolean found = false;
for (String f : newFileNames) {
if (f.equals(corruptFileName)) {
found = true;
break;
}
}
assertTrue(found);
}
// Fix the filesystem by moving corrupted files to lost+found
outStr = runFsck(conf, 1, true, "/", "-move", "-delete");
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
// Check to make sure we have healthy filesystem
outStr = runFsck(conf, 0, true, "/");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
util.cleanup(fs, topDir);
if (fs != null) {try{fs.close();} catch(Exception e){}}
cluster.shutdown();
} finally {
if (fs != null) {try{fs.close();} catch(Exception e){}}
if (cluster != null) { cluster.shutdown(); }
}
}
@Test
public void testFsckOpenFiles() throws Exception {
DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck").
setNumFiles(4).build();
MiniDFSCluster cluster = null;
FileSystem fs = null;
try {
Configuration conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
String topDir = "/srcdat";
String randomString = "HADOOP ";
fs = cluster.getFileSystem();
cluster.waitActive();
util.createFiles(fs, topDir);
util.waitReplication(fs, topDir, (short)3);
String outStr = runFsck(conf, 0, true, "/");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// Open a file for writing and do not close for now
Path openFile = new Path(topDir + "/openFile");
FSDataOutputStream out = fs.create(openFile);
int writeCount = 0;
while (writeCount != 100) {
out.write(randomString.getBytes());
writeCount++;
}
((DFSOutputStream) out.getWrappedStream()).hflush();
// We expect the filesystem to be HEALTHY and show one open file
outStr = runFsck(conf, 0, true, topDir);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertFalse(outStr.contains("OPENFORWRITE"));
// Use -openforwrite option to list open files
outStr = runFsck(conf, 0, true, topDir, "-files", "-blocks",
"-locations", "-openforwrite");
System.out.println(outStr);
assertTrue(outStr.contains("OPENFORWRITE"));
assertTrue(outStr.contains("Under Construction Block:"));
assertTrue(outStr.contains("openFile"));
// Close the file
out.close();
// Now, fsck should show HEALTHY fs and should not show any open files
outStr = runFsck(conf, 0, true, topDir);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertFalse(outStr.contains("OPENFORWRITE"));
assertFalse(outStr.contains("Under Construction Block:"));
util.cleanup(fs, topDir);
if (fs != null) {try{fs.close();} catch(Exception e){}}
cluster.shutdown();
} finally {
if (fs != null) {try{fs.close();} catch(Exception e){}}
if (cluster != null) { cluster.shutdown(); }
}
}
@Test
public void testFsckOpenECFiles() throws Exception {
DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsckECFile").
setNumFiles(4).build();
Configuration conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
ErasureCodingPolicy ecPolicy =
ErasureCodingPolicyManager.getSystemDefaultPolicy();
int numAllUnits = ecPolicy.getNumDataUnits() + ecPolicy.getNumParityUnits();
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(
numAllUnits + 1).build();
FileSystem fs = null;
try {
String topDir = "/myDir";
byte[] randomBytes = new byte[3000000];
int seed = 42;
new Random(seed).nextBytes(randomBytes);
cluster.waitActive();
fs = cluster.getFileSystem();
util.createFiles(fs, topDir);
// set topDir to EC when it has replicated files
cluster.getFileSystem().getClient().setErasureCodingPolicy(
topDir, ecPolicy);
// create a new file under topDir
DFSTestUtil.createFile(fs, new Path(topDir, "ecFile"), 1024, (short) 1, 0L);
// Open a EC file for writing and do not close for now
Path openFile = new Path(topDir + "/openECFile");
FSDataOutputStream out = fs.create(openFile);
int writeCount = 0;
while (writeCount != 300) {
out.write(randomBytes);
writeCount++;
}
// make sure the fsck can correctly handle mixed ec/replicated files
runFsck(conf, 0, true, topDir, "-files", "-blocks", "-openforwrite");
// We expect the filesystem to be HEALTHY and show one open file
String outStr = runFsck(conf, 0, true, openFile.toString(), "-files",
"-blocks", "-openforwrite");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertTrue(outStr.contains("OPENFORWRITE"));
assertTrue(outStr.contains("Live_repl=" + numAllUnits));
assertTrue(outStr.contains("Expected_repl=" + numAllUnits));
// Use -openforwrite option to list open files
outStr = runFsck(conf, 0, true, openFile.toString(), "-files", "-blocks",
"-locations", "-openforwrite", "-replicaDetails");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertTrue(outStr.contains("OPENFORWRITE"));
assertTrue(outStr.contains("Live_repl=" + numAllUnits));
assertTrue(outStr.contains("Expected_repl=" + numAllUnits));
assertTrue(outStr.contains("Under Construction Block:"));
// Close the file
out.close();
// Now, fsck should show HEALTHY fs and should not show any open files
outStr = runFsck(conf, 0, true, openFile.toString(), "-files", "-blocks",
"-locations", "-racks", "-replicaDetails");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertFalse(outStr.contains("OPENFORWRITE"));
assertFalse(outStr.contains("Under Construction Block:"));
assertFalse(outStr.contains("Expected_repl=" + numAllUnits));
assertTrue(outStr.contains("Live_repl=" + numAllUnits));
util.cleanup(fs, topDir);
} finally {
if (fs != null) {
try {
fs.close();
} catch (Exception e) {
}
}
if (cluster != null) {
cluster.shutdown();
}
}
}
@Test
public void testCorruptBlock() throws Exception {
Configuration conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
// Set short retry timeouts so this test runs faster
conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10);
FileSystem fs = null;
DFSClient dfsClient = null;
LocatedBlocks blocks = null;
int replicaCount = 0;
Random random = new Random();
String outStr = null;
short factor = 1;
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
cluster.waitActive();
fs = cluster.getFileSystem();
Path file1 = new Path("/testCorruptBlock");
DFSTestUtil.createFile(fs, file1, 1024, factor, 0);
// Wait until file replication has completed
DFSTestUtil.waitReplication(fs, file1, factor);
ExtendedBlock block = DFSTestUtil.getFirstBlock(fs, file1);
// Make sure filesystem is in healthy state
outStr = runFsck(conf, 0, true, "/");
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// corrupt replicas
File blockFile = cluster.getBlockFile(0, block);
if (blockFile != null && blockFile.exists()) {
RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
FileChannel channel = raFile.getChannel();
String badString = "BADBAD";
int rand = random.nextInt((int) channel.size()/2);
raFile.seek(rand);
raFile.write(badString.getBytes());
raFile.close();
}
// Read the file to trigger reportBadBlocks
try {
IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(), conf,
true);
} catch (IOException ie) {
// Ignore exception
}
dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
blocks = dfsClient.getNamenode().
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
replicaCount = blocks.get(0).getLocations().length;
while (replicaCount != factor) {
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
}
blocks = dfsClient.getNamenode().
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
replicaCount = blocks.get(0).getLocations().length;
}
assertTrue (blocks.get(0).isCorrupt());
// Check if fsck reports the same
outStr = runFsck(conf, 1, true, "/");
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
assertTrue(outStr.contains("testCorruptBlock"));
} finally {
if (cluster != null) {cluster.shutdown();}
}
}
@Test
public void testUnderMinReplicatedBlock() throws Exception {
Configuration conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
// Set short retry timeouts so this test runs faster
conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10);
// Set minReplication to 2
short minReplication=2;
conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY,minReplication);
FileSystem fs = null;
DFSClient dfsClient = null;
LocatedBlocks blocks = null;
int replicaCount = 0;
Random random = new Random();
String outStr = null;
short factor = 1;
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
cluster.waitActive();
fs = cluster.getFileSystem();
Path file1 = new Path("/testUnderMinReplicatedBlock");
DFSTestUtil.createFile(fs, file1, 1024, minReplication, 0);
// Wait until file replication has completed
DFSTestUtil.waitReplication(fs, file1, minReplication);
ExtendedBlock block = DFSTestUtil.getFirstBlock(fs, file1);
// Make sure filesystem is in healthy state
outStr = runFsck(conf, 0, true, "/");
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// corrupt the first replica
File blockFile = cluster.getBlockFile(0, block);
if (blockFile != null && blockFile.exists()) {
RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
FileChannel channel = raFile.getChannel();
String badString = "BADBAD";
int rand = random.nextInt((int) channel.size()/2);
raFile.seek(rand);
raFile.write(badString.getBytes());
raFile.close();
}
dfsClient = new DFSClient(new InetSocketAddress("localhost",
cluster.getNameNodePort()), conf);
blocks = dfsClient.getNamenode().
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
replicaCount = blocks.get(0).getLocations().length;
while (replicaCount != factor) {
try {
Thread.sleep(100);
// Read the file to trigger reportBadBlocks
try {
IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(), conf,
true);
} catch (IOException ie) {
// Ignore exception
}
System.out.println("sleep in try: replicaCount="+replicaCount+" factor="+factor);
} catch (InterruptedException ignore) {
}
blocks = dfsClient.getNamenode().
getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
replicaCount = blocks.get(0).getLocations().length;
}
// Check if fsck reports the same
outStr = runFsck(conf, 0, true, "/");
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertTrue(outStr.contains("UNDER MIN REPL'D BLOCKS:\t1 (100.0 %)"));
assertTrue(outStr.contains("dfs.namenode.replication.min:\t2"));
} finally {
if (cluster != null) {cluster.shutdown();}
}
}
@Test(timeout = 60000)
public void testFsckReplicaDetails() throws Exception {
final short REPL_FACTOR = 1;
short NUM_DN = 1;
final long blockSize = 512;
final long fileSize = 1024;
boolean checkDecommissionInProgress = false;
String[] racks = { "/rack1" };
String[] hosts = { "host1" };
Configuration conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
MiniDFSCluster cluster;
DistributedFileSystem dfs;
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts).racks(racks).build();
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
// create files
final String testFile = new String("/testfile");
final Path path = new Path(testFile);
DFSTestUtil.createFile(dfs, path, fileSize, REPL_FACTOR, 1000L);
DFSTestUtil.waitReplication(dfs, path, REPL_FACTOR);
try {
// make sure datanode that has replica is fine before decommission
String fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks", "-replicaDetails");
assertTrue(fsckOut.contains(NamenodeFsck.HEALTHY_STATUS));
assertTrue(fsckOut.contains("(LIVE)"));
// decommission datanode
ExtendedBlock eb = DFSTestUtil.getFirstBlock(dfs, path);
FSNamesystem fsn = cluster.getNameNode().getNamesystem();
BlockManager bm = fsn.getBlockManager();
BlockCollection bc = null;
try {
fsn.writeLock();
BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
bc = fsn.getBlockCollection(bi);
} finally {
fsn.writeUnlock();
}
DatanodeDescriptor dn = bc.getBlocks()[0]
.getDatanode(0);
bm.getDatanodeManager().getDecomManager().startDecommission(dn);
String dnName = dn.getXferAddr();
// check the replica status while decommissioning
fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks", "-replicaDetails");
assertTrue(fsckOut.contains("(DECOMMISSIONING)"));
// Start 2nd Datanode and wait for decommission to start
cluster.startDataNodes(conf, 1, true, null, null, null);
DatanodeInfo datanodeInfo = null;
do {
Thread.sleep(2000);
for (DatanodeInfo info : dfs.getDataNodeStats()) {
if (dnName.equals(info.getXferAddr())) {
datanodeInfo = info;
}
}
if (!checkDecommissionInProgress && datanodeInfo != null
&& datanodeInfo.isDecommissionInProgress()) {
checkDecommissionInProgress = true;
}
} while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
// check the replica status after decommission is done
fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks", "-replicaDetails");
assertTrue(fsckOut.contains("(DECOMMISSIONED)"));
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
/** Test if fsck can return -1 in case of failure
*
* @throws Exception
*/
@Test
public void testFsckError() throws Exception {
MiniDFSCluster cluster = null;
try {
// bring up a one-node cluster
Configuration conf = new HdfsConfiguration();
cluster = new MiniDFSCluster.Builder(conf).build();
String fileName = "/test.txt";
Path filePath = new Path(fileName);
FileSystem fs = cluster.getFileSystem();
// create a one-block file
DFSTestUtil.createFile(fs, filePath, 1L, (short)1, 1L);
DFSTestUtil.waitReplication(fs, filePath, (short)1);
// intentionally corrupt NN data structure
INodeFile node = (INodeFile) cluster.getNamesystem().dir.getINode
(fileName, true);
final BlockInfo[] blocks = node.getBlocks();
assertEquals(blocks.length, 1);
blocks[0].setNumBytes(-1L); // set the block length to be negative
// run fsck and expect a failure with -1 as the error code
String outStr = runFsck(conf, -1, true, fileName);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.FAILURE_STATUS));
// clean up file system
fs.delete(filePath, true);
} finally {
if (cluster != null) {cluster.shutdown();}
}
}
/** check if option -list-corruptfiles of fsck command works properly */
@Test
public void testFsckListCorruptFilesBlocks() throws Exception {
Configuration conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
FileSystem fs = null;
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf).build();
cluster.waitActive();
fs = cluster.getFileSystem();
DFSTestUtil util = new DFSTestUtil.Builder().
setName("testGetCorruptFiles").setNumFiles(3).setMaxLevels(1).
setMaxSize(1024).build();
util.createFiles(fs, "/corruptData", (short) 1);
util.waitReplication(fs, "/corruptData", (short) 1);
// String outStr = runFsck(conf, 0, true, "/corruptData", "-list-corruptfileblocks");
String outStr = runFsck(conf, 0, false, "/corruptData", "-list-corruptfileblocks");
System.out.println("1. good fsck out: " + outStr);
assertTrue(outStr.contains("has 0 CORRUPT files"));
// delete the blocks
final String bpid = cluster.getNamesystem().getBlockPoolId();
for (int i=0; i<4; i++) {
for (int j=0; j<=1; j++) {
File storageDir = cluster.getInstanceStorageDir(i, j);
File data_dir = MiniDFSCluster.getFinalizedDir(storageDir, bpid);
List<File> metadataFiles = MiniDFSCluster.getAllBlockMetadataFiles(
data_dir);
if (metadataFiles == null)
continue;
for (File metadataFile : metadataFiles) {
File blockFile = Block.metaToBlockFile(metadataFile);
assertTrue("Cannot remove file.", blockFile.delete());
assertTrue("Cannot remove file.", metadataFile.delete());
}
}
}
// wait for the namenode to see the corruption
final NamenodeProtocols namenode = cluster.getNameNodeRpc();
CorruptFileBlocks corruptFileBlocks = namenode
.listCorruptFileBlocks("/corruptData", null);
int numCorrupt = corruptFileBlocks.getFiles().length;
while (numCorrupt == 0) {
Thread.sleep(1000);
corruptFileBlocks = namenode
.listCorruptFileBlocks("/corruptData", null);
numCorrupt = corruptFileBlocks.getFiles().length;
}
outStr = runFsck(conf, -1, true, "/corruptData", "-list-corruptfileblocks");
System.out.println("2. bad fsck out: " + outStr);
assertTrue(outStr.contains("has 3 CORRUPT files"));
// Do a listing on a dir which doesn't have any corrupt blocks and validate
util.createFiles(fs, "/goodData");
outStr = runFsck(conf, 0, true, "/goodData", "-list-corruptfileblocks");
System.out.println("3. good fsck out: " + outStr);
assertTrue(outStr.contains("has 0 CORRUPT files"));
util.cleanup(fs,"/corruptData");
util.cleanup(fs, "/goodData");
} finally {
if (cluster != null) {cluster.shutdown();}
}
}
/**
* Test for checking fsck command on illegal arguments should print the proper
* usage.
*/
@Test
public void testToCheckTheFsckCommandOnIllegalArguments() throws Exception {
MiniDFSCluster cluster = null;
try {
// bring up a one-node cluster
Configuration conf = new HdfsConfiguration();
cluster = new MiniDFSCluster.Builder(conf).build();
String fileName = "/test.txt";
Path filePath = new Path(fileName);
FileSystem fs = cluster.getFileSystem();
// create a one-block file
DFSTestUtil.createFile(fs, filePath, 1L, (short) 1, 1L);
DFSTestUtil.waitReplication(fs, filePath, (short) 1);
// passing illegal option
String outStr = runFsck(conf, -1, true, fileName, "-thisIsNotAValidFlag");
System.out.println(outStr);
assertTrue(!outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// passing multiple paths are arguments
outStr = runFsck(conf, -1, true, "/", fileName);
System.out.println(outStr);
assertTrue(!outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// clean up file system
fs.delete(filePath, true);
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
/**
* Tests that the # of missing block replicas and expected replicas is correct
* @throws IOException
*/
@Test
public void testFsckMissingReplicas() throws IOException {
// Desired replication factor
// Set this higher than NUM_REPLICAS so it's under-replicated
final short REPL_FACTOR = 2;
// Number of replicas to actually start
final short NUM_REPLICAS = 1;
// Number of blocks to write
final short NUM_BLOCKS = 3;
// Set a small-ish blocksize
final long blockSize = 512;
Configuration conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
MiniDFSCluster cluster = null;
DistributedFileSystem dfs = null;
try {
// Startup a minicluster
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(NUM_REPLICAS).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
// Create a file that will be intentionally under-replicated
final String pathString = new String("/testfile");
final Path path = new Path(pathString);
long fileLen = blockSize * NUM_BLOCKS;
DFSTestUtil.createFile(dfs, path, fileLen, REPL_FACTOR, 1);
// Create an under-replicated file
NameNode namenode = cluster.getNameNode();
NetworkTopology nettop = cluster.getNamesystem().getBlockManager()
.getDatanodeManager().getNetworkTopology();
Map<String,String[]> pmap = new HashMap<String, String[]>();
Writer result = new StringWriter();
PrintWriter out = new PrintWriter(result, true);
InetAddress remoteAddress = InetAddress.getLocalHost();
NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
NUM_REPLICAS, remoteAddress);
// Run the fsck and check the Result
final HdfsFileStatus file =
namenode.getRpcServer().getFileInfo(pathString);
assertNotNull(file);
Result replRes = new ReplicationResult(conf);
Result ecRes = new ErasureCodingResult(conf);
fsck.check(pathString, file, replRes, ecRes);
// Also print the output from the fsck, for ex post facto sanity checks
System.out.println(result.toString());
assertEquals(replRes.missingReplicas,
(NUM_BLOCKS*REPL_FACTOR) - (NUM_BLOCKS*NUM_REPLICAS));
assertEquals(replRes.numExpectedReplicas, NUM_BLOCKS*REPL_FACTOR);
} finally {
if(dfs != null) {
dfs.close();
}
if(cluster != null) {
cluster.shutdown();
}
}
}
/**
* Tests that the # of misreplaced replicas is correct
* @throws IOException
*/
@Test
public void testFsckMisPlacedReplicas() throws IOException {
// Desired replication factor
final short REPL_FACTOR = 2;
// Number of replicas to actually start
short NUM_DN = 2;
// Number of blocks to write
final short NUM_BLOCKS = 3;
// Set a small-ish blocksize
final long blockSize = 512;
String [] racks = {"/rack1", "/rack1"};
String [] hosts = {"host1", "host2"};
Configuration conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
MiniDFSCluster cluster = null;
DistributedFileSystem dfs = null;
try {
// Startup a minicluster
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts)
.racks(racks).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
// Create a file that will be intentionally under-replicated
final String pathString = new String("/testfile");
final Path path = new Path(pathString);
long fileLen = blockSize * NUM_BLOCKS;
DFSTestUtil.createFile(dfs, path, fileLen, REPL_FACTOR, 1);
// Create an under-replicated file
NameNode namenode = cluster.getNameNode();
NetworkTopology nettop = cluster.getNamesystem().getBlockManager()
.getDatanodeManager().getNetworkTopology();
// Add a new node on different rack, so previous blocks' replicas
// are considered to be misplaced
nettop.add(DFSTestUtil.getDatanodeDescriptor("/rack2", "/host3"));
NUM_DN++;
Map<String,String[]> pmap = new HashMap<String, String[]>();
Writer result = new StringWriter();
PrintWriter out = new PrintWriter(result, true);
InetAddress remoteAddress = InetAddress.getLocalHost();
NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
NUM_DN, remoteAddress);
// Run the fsck and check the Result
final HdfsFileStatus file =
namenode.getRpcServer().getFileInfo(pathString);
assertNotNull(file);
Result replRes = new ReplicationResult(conf);
Result ecRes = new ErasureCodingResult(conf);
fsck.check(pathString, file, replRes, ecRes);
// check misReplicatedBlock number.
assertEquals(replRes.numMisReplicatedBlocks, NUM_BLOCKS);
} finally {
if(dfs != null) {
dfs.close();
}
if(cluster != null) {
cluster.shutdown();
}
}
}
/** Test fsck with FileNotFound */
@Test
public void testFsckFileNotFound() throws Exception {
// Number of replicas to actually start
final short NUM_REPLICAS = 1;
Configuration conf = new Configuration();
NameNode namenode = mock(NameNode.class);
NetworkTopology nettop = mock(NetworkTopology.class);
Map<String,String[]> pmap = new HashMap<>();
Writer result = new StringWriter();
PrintWriter out = new PrintWriter(result, true);
InetAddress remoteAddress = InetAddress.getLocalHost();
FSNamesystem fsName = mock(FSNamesystem.class);
FSDirectory fsd = mock(FSDirectory.class);
BlockManager blockManager = mock(BlockManager.class);
DatanodeManager dnManager = mock(DatanodeManager.class);
INodesInPath iip = mock(INodesInPath.class);
when(namenode.getNamesystem()).thenReturn(fsName);
when(fsName.getBlockManager()).thenReturn(blockManager);
when(fsName.getFSDirectory()).thenReturn(fsd);
when(fsd.getFSNamesystem()).thenReturn(fsName);
when(fsd.resolvePath(anyObject(), anyString())).thenReturn(iip);
when(blockManager.getDatanodeManager()).thenReturn(dnManager);
NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
NUM_REPLICAS, remoteAddress);
String pathString = "/tmp/testFile";
long length = 123L;
boolean isDir = false;
int blockReplication = 1;
long blockSize = 128 *1024L;
long modTime = 123123123L;
long accessTime = 123123120L;
FsPermission perms = FsPermission.getDefault();
String owner = "foo";
String group = "bar";
byte [] symlink = null;
byte [] path = DFSUtil.string2Bytes(pathString);
long fileId = 312321L;
int numChildren = 1;
byte storagePolicy = 0;
HdfsFileStatus file = new HdfsFileStatus(length, isDir, blockReplication,
blockSize, modTime, accessTime, perms, owner, group, symlink,
path, fileId, numChildren, null, storagePolicy, null);
Result replRes = new ReplicationResult(conf);
Result ecRes = new ErasureCodingResult(conf);
try {
fsck.check(pathString, file, replRes, ecRes);
} catch (Exception e) {
fail("Unexpected exception " + e.getMessage());
}
assertTrue(replRes.isHealthy());
}
/** Test fsck with symlinks in the filesystem */
@Test
public void testFsckSymlink() throws Exception {
final DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(1).build();
final Configuration conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
MiniDFSCluster cluster = null;
FileSystem fs = null;
try {
final long precision = 1L;
conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, precision);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
fs = cluster.getFileSystem();
final String fileName = "/srcdat";
util.createFiles(fs, fileName);
final FileContext fc = FileContext.getFileContext(
cluster.getConfiguration(0));
final Path file = new Path(fileName);
final Path symlink = new Path("/srcdat-symlink");
fc.createSymlink(file, symlink, false);
util.waitReplication(fs, fileName, (short)3);
long aTime = fc.getFileStatus(symlink).getAccessTime();
Thread.sleep(precision);
setupAuditLogs();
String outStr = runFsck(conf, 0, true, "/");
verifyAuditLogs();
assertEquals(aTime, fc.getFileStatus(symlink).getAccessTime());
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
assertTrue(outStr.contains("Total symlinks:\t\t1"));
util.cleanup(fs, fileName);
} finally {
if (fs != null) {try{fs.close();} catch(Exception e){}}
if (cluster != null) { cluster.shutdown(); }
}
}
/**
* Test for including the snapshot files in fsck report
*/
@Test
public void testFsckForSnapshotFiles() throws Exception {
final Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1)
.build();
try {
String runFsck = runFsck(conf, 0, true, "/", "-includeSnapshots",
"-files");
assertTrue(runFsck.contains("HEALTHY"));
final String fileName = "/srcdat";
DistributedFileSystem hdfs = cluster.getFileSystem();
Path file1 = new Path(fileName);
DFSTestUtil.createFile(hdfs, file1, 1024, (short) 1, 1000L);
hdfs.allowSnapshot(new Path("/"));
hdfs.createSnapshot(new Path("/"), "mySnapShot");
runFsck = runFsck(conf, 0, true, "/", "-includeSnapshots", "-files");
assertTrue(runFsck.contains("/.snapshot/mySnapShot/srcdat"));
runFsck = runFsck(conf, 0, true, "/", "-files");
assertFalse(runFsck.contains("mySnapShot"));
} finally {
cluster.shutdown();
}
}
/**
* Test for blockIdCK
*/
@Test
public void testBlockIdCK() throws Exception {
final short REPL_FACTOR = 2;
short NUM_DN = 2;
final long blockSize = 512;
String [] racks = {"/rack1", "/rack2"};
String [] hosts = {"host1", "host2"};
Configuration conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 2);
MiniDFSCluster cluster = null;
DistributedFileSystem dfs = null;
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts)
.racks(racks).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(1).build();
//create files
final String pathString = new String("/testfile");
final Path path = new Path(pathString);
util.createFile(dfs, path, 1024, REPL_FACTOR , 1000L);
util.waitReplication(dfs, path, REPL_FACTOR);
StringBuilder sb = new StringBuilder();
for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
}
String[] bIds = sb.toString().split(" ");
//run fsck
try {
//illegal input test
String runFsckResult = runFsck(conf, 0, true, "/", "-blockId",
"not_a_block_id");
assertTrue(runFsckResult.contains("Incorrect blockId format:"));
//general test
runFsckResult = runFsck(conf, 0, true, "/", "-blockId", sb.toString());
assertTrue(runFsckResult.contains(bIds[0]));
assertTrue(runFsckResult.contains(bIds[1]));
assertTrue(runFsckResult.contains(
"Block replica on datanode/rack: host1/rack1 is HEALTHY"));
assertTrue(runFsckResult.contains(
"Block replica on datanode/rack: host2/rack2 is HEALTHY"));
} finally {
cluster.shutdown();
}
}
/**
* Test for blockIdCK with datanode decommission
*/
@Test
public void testBlockIdCKDecommission() throws Exception {
final short REPL_FACTOR = 1;
short NUM_DN = 2;
final long blockSize = 512;
boolean checkDecommissionInProgress = false;
String [] racks = {"/rack1", "/rack2"};
String [] hosts = {"host1", "host2"};
Configuration conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 2);
MiniDFSCluster cluster;
DistributedFileSystem dfs ;
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts)
.racks(racks).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(1).build();
//create files
final String pathString = new String("/testfile");
final Path path = new Path(pathString);
util.createFile(dfs, path, 1024, REPL_FACTOR, 1000L);
util.waitReplication(dfs, path, REPL_FACTOR);
StringBuilder sb = new StringBuilder();
for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
}
String[] bIds = sb.toString().split(" ");
try {
//make sure datanode that has replica is fine before decommission
String outStr = runFsck(conf, 0, true, "/", "-blockId", bIds[0]);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
//decommission datanode
FSNamesystem fsn = cluster.getNameNode().getNamesystem();
BlockManager bm = fsn.getBlockManager();
ExtendedBlock eb = util.getFirstBlock(dfs, path);
BlockCollection bc = null;
try {
fsn.writeLock();
BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
bc = fsn.getBlockCollection(bi);
} finally {
fsn.writeUnlock();
}
DatanodeDescriptor dn = bc.getBlocks()[0].getDatanode(0);
bm.getDatanodeManager().getDecomManager().startDecommission(dn);
String dnName = dn.getXferAddr();
//wait for decommission start
DatanodeInfo datanodeInfo = null;
int count = 0;
do {
Thread.sleep(2000);
for (DatanodeInfo info : dfs.getDataNodeStats()) {
if (dnName.equals(info.getXferAddr())) {
datanodeInfo = info;
}
}
//check decommissioning only once
if(!checkDecommissionInProgress && datanodeInfo != null
&& datanodeInfo.isDecommissionInProgress()) {
String fsckOut = runFsck(conf, 3, true, "/", "-blockId", bIds[0]);
assertTrue(fsckOut.contains(NamenodeFsck.DECOMMISSIONING_STATUS));
checkDecommissionInProgress = true;
}
} while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
//check decommissioned
String fsckOut = runFsck(conf, 2, true, "/", "-blockId", bIds[0]);
assertTrue(fsckOut.contains(NamenodeFsck.DECOMMISSIONED_STATUS));
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
/**
* Test for blockIdCK with block corruption
*/
@Test
public void testBlockIdCKCorruption() throws Exception {
short NUM_DN = 1;
final long blockSize = 512;
Random random = new Random();
ExtendedBlock block;
short repFactor = 1;
String [] racks = {"/rack1"};
String [] hosts = {"host1"};
Configuration conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
// Set short retry timeouts so this test runs faster
conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10);
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
MiniDFSCluster cluster = null;
DistributedFileSystem dfs = null;
try {
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts)
.racks(racks).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(1).build();
//create files
final String pathString = new String("/testfile");
final Path path = new Path(pathString);
util.createFile(dfs, path, 1024, repFactor, 1000L);
util.waitReplication(dfs, path, repFactor);
StringBuilder sb = new StringBuilder();
for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
}
String[] bIds = sb.toString().split(" ");
//make sure block is healthy before we corrupt it
String outStr = runFsck(conf, 0, true, "/", "-blockId", bIds[0]);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// corrupt replicas
block = DFSTestUtil.getFirstBlock(dfs, path);
File blockFile = cluster.getBlockFile(0, block);
if (blockFile != null && blockFile.exists()) {
RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
FileChannel channel = raFile.getChannel();
String badString = "BADBAD";
int rand = random.nextInt((int) channel.size()/2);
raFile.seek(rand);
raFile.write(badString.getBytes());
raFile.close();
}
util.waitCorruptReplicas(dfs, cluster.getNamesystem(), path, block, 1);
outStr = runFsck(conf, 1, false, "/", "-blockId", block.getBlockName());
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
private void writeFile(final DistributedFileSystem dfs,
Path dir, String fileName) throws IOException {
Path filePath = new Path(dir.toString() + Path.SEPARATOR + fileName);
final FSDataOutputStream out = dfs.create(filePath);
out.writeChars("teststring");
out.close();
}
private void writeFile(final DistributedFileSystem dfs,
String dirName, String fileName, String StoragePolicy) throws IOException {
Path dirPath = new Path(dirName);
dfs.mkdirs(dirPath);
dfs.setStoragePolicy(dirPath, StoragePolicy);
writeFile(dfs, dirPath, fileName);
}
/**
* Test storage policy display
*/
@Test
public void testStoragePoliciesCK() throws Exception {
final Configuration conf = new HdfsConfiguration();
final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(3)
.storageTypes(
new StorageType[] {StorageType.DISK, StorageType.ARCHIVE})
.build();
try {
cluster.waitActive();
final DistributedFileSystem dfs = cluster.getFileSystem();
writeFile(dfs, "/testhot", "file", "HOT");
writeFile(dfs, "/testwarm", "file", "WARM");
writeFile(dfs, "/testcold", "file", "COLD");
String outStr = runFsck(conf, 0, true, "/", "-storagepolicies");
assertTrue(outStr.contains("DISK:3(HOT)"));
assertTrue(outStr.contains("DISK:1,ARCHIVE:2(WARM)"));
assertTrue(outStr.contains("ARCHIVE:3(COLD)"));
assertTrue(outStr.contains("All blocks satisfy specified storage policy."));
dfs.setStoragePolicy(new Path("/testhot"), "COLD");
dfs.setStoragePolicy(new Path("/testwarm"), "COLD");
outStr = runFsck(conf, 0, true, "/", "-storagepolicies");
assertTrue(outStr.contains("DISK:3(HOT)"));
assertTrue(outStr.contains("DISK:1,ARCHIVE:2(WARM)"));
assertTrue(outStr.contains("ARCHIVE:3(COLD)"));
assertFalse(outStr.contains("All blocks satisfy specified storage policy."));
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
/**
* Test for blocks on decommissioning hosts are not shown as missing
*/
@Test
public void testFsckWithDecommissionedReplicas() throws Exception {
final short REPL_FACTOR = 1;
short NUM_DN = 2;
final long blockSize = 512;
final long fileSize = 1024;
boolean checkDecommissionInProgress = false;
String [] racks = {"/rack1", "/rack2"};
String [] hosts = {"host1", "host2"};
Configuration conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
MiniDFSCluster cluster;
DistributedFileSystem dfs ;
cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts)
.racks(racks).build();
assertNotNull("Failed Cluster Creation", cluster);
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
assertNotNull("Failed to get FileSystem", dfs);
DFSTestUtil util = new DFSTestUtil.Builder().
setName(getClass().getSimpleName()).setNumFiles(1).build();
//create files
final String testFile = new String("/testfile");
final Path path = new Path(testFile);
util.createFile(dfs, path, fileSize, REPL_FACTOR, 1000L);
util.waitReplication(dfs, path, REPL_FACTOR);
try {
// make sure datanode that has replica is fine before decommission
String outStr = runFsck(conf, 0, true, testFile);
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// decommission datanode
FSNamesystem fsn = cluster.getNameNode().getNamesystem();
BlockManager bm = fsn.getBlockManager();
ExtendedBlock eb = util.getFirstBlock(dfs, path);
BlockCollection bc = null;
try {
fsn.writeLock();
BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
bc = fsn.getBlockCollection(bi);
} finally {
fsn.writeUnlock();
}
DatanodeDescriptor dn = bc.getBlocks()[0]
.getDatanode(0);
bm.getDatanodeManager().getDecomManager().startDecommission(dn);
String dnName = dn.getXferAddr();
// wait for decommission start
DatanodeInfo datanodeInfo = null;
int count = 0;
do {
Thread.sleep(2000);
for (DatanodeInfo info : dfs.getDataNodeStats()) {
if (dnName.equals(info.getXferAddr())) {
datanodeInfo = info;
}
}
// check the replica status should be healthy(0)
// instead of corruption (1) during decommissioning
if(!checkDecommissionInProgress && datanodeInfo != null
&& datanodeInfo.isDecommissionInProgress()) {
String fsckOut = runFsck(conf, 0, true, testFile);
checkDecommissionInProgress = true;
}
} while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
// check the replica status should be healthy(0) after decommission
// is done
String fsckOut = runFsck(conf, 0, true, testFile);
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
@Test
public void testECFsck() throws Exception {
MiniDFSCluster cluster = null;
FileSystem fs = null;
try {
Configuration conf = new HdfsConfiguration();
final long precision = 1L;
conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, precision);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
int totalSize = ErasureCodingPolicyManager.getSystemDefaultPolicy().getNumDataUnits()
+ ErasureCodingPolicyManager.getSystemDefaultPolicy().getNumParityUnits();
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(totalSize).build();
fs = cluster.getFileSystem();
// create a contiguous file
Path replDirPath = new Path("/replicated");
Path replFilePath = new Path(replDirPath, "replfile");
final short factor = 3;
DFSTestUtil.createFile(fs, replFilePath, 1024, factor, 0);
DFSTestUtil.waitReplication(fs, replFilePath, factor);
// create a large striped file
Path ecDirPath = new Path("/striped");
Path largeFilePath = new Path(ecDirPath, "largeFile");
DFSTestUtil.createStripedFile(cluster, largeFilePath, ecDirPath, 1, 2, true);
// create a small striped file
Path smallFilePath = new Path(ecDirPath, "smallFile");
DFSTestUtil.writeFile(fs, smallFilePath, "hello world!");
long replTime = fs.getFileStatus(replFilePath).getAccessTime();
long ecTime = fs.getFileStatus(largeFilePath).getAccessTime();
Thread.sleep(precision);
setupAuditLogs();
String outStr = runFsck(conf, 0, true, "/");
verifyAuditLogs();
assertEquals(replTime, fs.getFileStatus(replFilePath).getAccessTime());
assertEquals(ecTime, fs.getFileStatus(largeFilePath).getAccessTime());
System.out.println(outStr);
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
if (fs != null) {try{fs.close();} catch(Exception e){}}
cluster.shutdown();
// restart the cluster; bring up namenode but not the data nodes
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0).format(false).build();
outStr = runFsck(conf, 1, true, "/");
// expect the result is corrupt
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
System.out.println(outStr);
} finally {
if (fs != null) {try{fs.close();} catch(Exception e){}}
if (cluster != null) { cluster.shutdown(); }
}
}
/**
* Test that corrupted snapshot files are listed with full dir.
*/
@Test
public void testFsckListCorruptSnapshotFiles() throws Exception {
Configuration conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
DistributedFileSystem hdfs = null;
final short REPL_FACTOR = 1;
MiniDFSCluster cluster = null;
try {
int numFiles = 3;
int numSnapshots = 0;
cluster = new MiniDFSCluster.Builder(conf).build();
cluster.waitActive();
hdfs = cluster.getFileSystem();
DFSTestUtil util = new DFSTestUtil.Builder().
setName("testGetCorruptFiles").setNumFiles(numFiles).setMaxLevels(1).
setMaxSize(1024).build();
util.createFiles(hdfs, "/corruptData", (short) 1);
final Path fp = new Path("/corruptData/file");
util.createFile(hdfs, fp, 1024, REPL_FACTOR, 1000L);
numFiles++;
util.waitReplication(hdfs, "/corruptData", (short) 1);
hdfs.allowSnapshot(new Path("/corruptData"));
hdfs.createSnapshot(new Path("/corruptData"), "mySnapShot");
numSnapshots = numFiles;
String outStr =
runFsck(conf, 0, false, "/corruptData", "-list-corruptfileblocks");
System.out.println("1. good fsck out: " + outStr);
assertTrue(outStr.contains("has 0 CORRUPT files"));
// delete the blocks
final String bpid = cluster.getNamesystem().getBlockPoolId();
for (int i=0; i<numFiles; i++) {
for (int j=0; j<=1; j++) {
File storageDir = cluster.getInstanceStorageDir(i, j);
File data_dir = MiniDFSCluster.getFinalizedDir(storageDir, bpid);
List<File> metadataFiles = MiniDFSCluster.getAllBlockMetadataFiles(
data_dir);
if (metadataFiles == null)
continue;
for (File metadataFile : metadataFiles) {
File blockFile = Block.metaToBlockFile(metadataFile);
assertTrue("Cannot remove file.", blockFile.delete());
assertTrue("Cannot remove file.", metadataFile.delete());
}
}
}
// Delete file when it has a snapshot
hdfs.delete(fp, false);
numFiles--;
// wait for the namenode to see the corruption
final NamenodeProtocols namenode = cluster.getNameNodeRpc();
CorruptFileBlocks corruptFileBlocks = namenode
.listCorruptFileBlocks("/corruptData", null);
int numCorrupt = corruptFileBlocks.getFiles().length;
while (numCorrupt == 0) {
Thread.sleep(1000);
corruptFileBlocks = namenode
.listCorruptFileBlocks("/corruptData", null);
numCorrupt = corruptFileBlocks.getFiles().length;
}
// with -includeSnapshots all files are reported
outStr = runFsck(conf, -1, true, "/corruptData",
"-list-corruptfileblocks", "-includeSnapshots");
System.out.println("2. bad fsck include snapshot out: " + outStr);
assertTrue(outStr
.contains("has " + (numFiles + numSnapshots) + " CORRUPT files"));
assertTrue(outStr.contains("/.snapshot/"));
// without -includeSnapshots only non-snapshots are reported
outStr =
runFsck(conf, -1, true, "/corruptData", "-list-corruptfileblocks");
System.out.println("3. bad fsck exclude snapshot out: " + outStr);
assertTrue(outStr.contains("has " + numFiles + " CORRUPT files"));
assertFalse(outStr.contains("/.snapshot/"));
} finally {
if (cluster != null) {cluster.shutdown();}
}
}
@Test (timeout = 300000)
public void testFsckMoveAfterCorruption() throws Exception {
final int DFS_BLOCK_SIZE = 512 * 1024;
final int NUM_DATANODES = 1;
final int REPLICATION = 1;
MiniDFSCluster cluster = null;
try {
final Configuration conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DFS_BLOCK_SIZE);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000L);
conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, REPLICATION);
cluster = new MiniDFSCluster.Builder(conf).build();
DistributedFileSystem dfs = cluster.getFileSystem();
cluster.waitActive();
final String srcDir = "/srcdat";
final DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck")
.setMinSize(DFS_BLOCK_SIZE * 2).setMaxSize(DFS_BLOCK_SIZE * 3)
.setNumFiles(1).build();
util.createFiles(dfs, srcDir, (short) REPLICATION);
final String fileNames[] = util.getFileNames(srcDir);
FSImage.LOG.info("Created files: " + Arrays.toString(fileNames));
// Run fsck here. The output is automatically logged for easier debugging
String outStr = runFsck(conf, 0, true, "/", "-files", "-blocks");
assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
// Corrupt the first block
final DFSClient dfsClient = new DFSClient(
new InetSocketAddress("localhost", cluster.getNameNodePort()), conf);
final String blockFileToCorrupt = fileNames[0];
final CorruptedTestFile ctf = new CorruptedTestFile(blockFileToCorrupt,
Sets.newHashSet(0), dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE);
ctf.corruptBlocks(cluster);
// Wait for fsck to discover all the missing blocks
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
try {
final String str = runFsck(conf, 1, false, "/");
String numCorrupt = null;
for (String line : str.split(LINE_SEPARATOR)) {
Matcher m = numCorruptBlocksPattern.matcher(line);
if (m.matches()) {
numCorrupt = m.group(1);
break;
}
}
if (numCorrupt == null) {
Assert.fail("Cannot find corrupt blocks count in fsck output.");
}
if (Integer.parseInt(numCorrupt) == ctf.getTotalMissingBlocks()) {
assertTrue(str.contains(NamenodeFsck.CORRUPT_STATUS));
return true;
}
} catch (Exception e) {
FSImage.LOG.error("Exception caught", e);
Assert.fail("Caught unexpected exception.");
}
return false;
}
}, 1000, 60000);
runFsck(conf, 1, true, "/", "-files", "-blocks", "-racks");
FSImage.LOG.info("Moving blocks to lost+found");
// Fsck will return error since we corrupted a block
runFsck(conf, 1, false, "/", "-move");
final List<LocatedFileStatus> retVal = new ArrayList<>();
final RemoteIterator<LocatedFileStatus> iter =
dfs.listFiles(new Path("/lost+found"), true);
while (iter.hasNext()) {
retVal.add(iter.next());
}
FSImage.LOG.info("Items in lost+found: " + retVal);
// Expect all good blocks moved, only corrupted block skipped.
long totalLength = 0;
for (LocatedFileStatus lfs: retVal) {
totalLength += lfs.getLen();
}
Assert.assertTrue("Nothing is moved to lost+found!", totalLength > 0);
util.cleanup(dfs, srcDir);
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
@Test(timeout = 60000)
public void testFsckUpgradeDomain() throws Exception {
testUpgradeDomain(false, false);
testUpgradeDomain(false, true);
testUpgradeDomain(true, false);
testUpgradeDomain(true, true);
}
private void testUpgradeDomain(boolean defineUpgradeDomain,
boolean displayUpgradeDomain) throws Exception {
final short replFactor = 1;
final short numDN = 1;
final long blockSize = 512;
final long fileSize = 1024;
final String upgradeDomain = "ud1";
final String[] racks = {"/rack1"};
final String[] hosts = {"127.0.0.1"};
HostsFileWriter hostsFileWriter = new HostsFileWriter();
Configuration conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, replFactor);
if (defineUpgradeDomain) {
conf.setClass(DFSConfigKeys.DFS_NAMENODE_HOSTS_PROVIDER_CLASSNAME_KEY,
CombinedHostFileManager.class, HostConfigManager.class);
hostsFileWriter.initialize(conf, "temp/fsckupgradedomain");
}
MiniDFSCluster cluster;
DistributedFileSystem dfs;
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDN).
hosts(hosts).racks(racks).build();
cluster.waitClusterUp();
dfs = cluster.getFileSystem();
// Configure the upgrade domain on the datanode
if (defineUpgradeDomain) {
DatanodeAdminProperties dnProp = new DatanodeAdminProperties();
DatanodeID datanodeID = cluster.getDataNodes().get(0).getDatanodeId();
dnProp.setHostName(datanodeID.getHostName());
dnProp.setPort(datanodeID.getXferPort());
dnProp.setUpgradeDomain(upgradeDomain);
hostsFileWriter.initIncludeHosts(new DatanodeAdminProperties[]{dnProp});
cluster.getFileSystem().refreshNodes();
}
// create files
final String testFile = new String("/testfile");
final Path path = new Path(testFile);
DFSTestUtil.createFile(dfs, path, fileSize, replFactor, 1000L);
DFSTestUtil.waitReplication(dfs, path, replFactor);
try {
String fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks",
displayUpgradeDomain ? "-upgradedomains" : "-locations");
assertTrue(fsckOut.contains(NamenodeFsck.HEALTHY_STATUS));
String udValue = defineUpgradeDomain ? upgradeDomain :
NamenodeFsck.UNDEFINED;
assertEquals(displayUpgradeDomain,
fsckOut.contains("(ud=" + udValue + ")"));
} finally {
if (defineUpgradeDomain) {
hostsFileWriter.cleanup();
}
if (cluster != null) {
cluster.shutdown();
}
}
}
@Test (timeout = 300000)
public void testFsckCorruptECFile() throws Exception {
MiniDFSCluster cluster = null;
DistributedFileSystem fs = null;
try {
Configuration conf = new HdfsConfiguration();
int dataBlocks = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getNumDataUnits();
int parityBlocks = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getNumParityUnits();
int cellSize = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getCellSize();
int totalSize = dataBlocks + parityBlocks;
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(totalSize).build();
fs = cluster.getFileSystem();
Map<Integer, Integer> dnIndices = new HashMap<>();
ArrayList<DataNode> dnList = cluster.getDataNodes();
for (int i = 0; i < totalSize; i++) {
dnIndices.put(dnList.get(i).getIpcPort(), i);
}
// create file
Path ecDirPath = new Path("/striped");
fs.mkdir(ecDirPath, FsPermission.getDirDefault());
fs.getClient().setErasureCodingPolicy(ecDirPath.toString(), null);
Path file = new Path(ecDirPath, "corrupted");
final int length = cellSize * dataBlocks;
final byte[] bytes = StripedFileTestUtil.generateBytes(length);
DFSTestUtil.writeFile(fs, file, bytes);
LocatedStripedBlock lsb = (LocatedStripedBlock)fs.getClient()
.getLocatedBlocks(file.toString(), 0, cellSize * dataBlocks).get(0);
final LocatedBlock[] blks = StripedBlockUtil.parseStripedBlockGroup(lsb,
cellSize, dataBlocks, parityBlocks);
// make an unrecoverable ec file with corrupted blocks
for(int i = 0; i < parityBlocks + 1; i++) {
int ipcPort = blks[i].getLocations()[0].getIpcPort();
int dnIndex = dnIndices.get(ipcPort);
File storageDir = cluster.getInstanceStorageDir(dnIndex, 0);
File blkFile = MiniDFSCluster.getBlockFile(storageDir,
blks[i].getBlock());
Assert.assertTrue("Block file does not exist", blkFile.exists());
FileOutputStream out = new FileOutputStream(blkFile);
out.write("corruption".getBytes());
}
// disable the heart beat from DN so that the corrupted block record is
// kept in NameNode
for (DataNode dn : cluster.getDataNodes()) {
DataNodeTestUtils.setHeartbeatsDisabledForTests(dn, true);
}
// Read the file to trigger reportBadBlocks
try {
IOUtils.copyBytes(fs.open(file), new IOUtils.NullOutputStream(), conf,
true);
} catch (IOException ie) {
assertTrue(ie.getMessage().contains(
"missingChunksNum=" + (parityBlocks + 1)));
}
waitForUnrecoverableBlockGroup(conf);
String outStr = runFsck(conf, 1, true, "/");
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
} finally {
if (fs != null) {
try {
fs.close();
} catch (Exception e) {
}
}
if (cluster != null) {
cluster.shutdown();
}
}
}
@Test (timeout = 300000)
public void testFsckMissingECFile() throws Exception {
MiniDFSCluster cluster = null;
DistributedFileSystem fs = null;
try {
Configuration conf = new HdfsConfiguration();
int dataBlocks = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getNumDataUnits();
int parityBlocks = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getNumParityUnits();
int cellSize = ErasureCodingPolicyManager
.getSystemDefaultPolicy().getCellSize();
int totalSize = dataBlocks + parityBlocks;
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(totalSize).build();
fs = cluster.getFileSystem();
// create file
Path ecDirPath = new Path("/striped");
fs.mkdir(ecDirPath, FsPermission.getDirDefault());
fs.getClient().setErasureCodingPolicy(ecDirPath.toString(), null);
Path file = new Path(ecDirPath, "missing");
final int length = cellSize * dataBlocks;
final byte[] bytes = StripedFileTestUtil.generateBytes(length);
DFSTestUtil.writeFile(fs, file, bytes);
// make an unrecoverable ec file with missing blocks
ArrayList<DataNode> dns = cluster.getDataNodes();
DatanodeID dnId;
for (int i = 0; i < parityBlocks + 1; i++) {
dnId = dns.get(i).getDatanodeId();
cluster.stopDataNode(dnId.getXferAddr());
cluster.setDataNodeDead(dnId);
}
waitForUnrecoverableBlockGroup(conf);
String outStr = runFsck(conf, 1, true, "/", "-files", "-blocks",
"-locations");
assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
assertTrue(outStr.contains("Live_repl=" + (dataBlocks - 1)));
} finally {
if (fs != null) {
try {
fs.close();
} catch (Exception e) {
}
}
if (cluster != null) {
cluster.shutdown();
}
}
}
private void waitForUnrecoverableBlockGroup(Configuration conf)
throws TimeoutException, InterruptedException {
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
try {
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bStream, true);
ToolRunner.run(new DFSck(conf, out), new String[] {"/"});
String outStr = bStream.toString();
if (outStr.contains("UNRECOVERABLE BLOCK GROUPS")) {
return true;
}
} catch (Exception e) {
FSImage.LOG.error("Exception caught", e);
Assert.fail("Caught unexpected exception.");
}
return false;
}
}, 1000, 60000);
}
}
| HDFS-10933. Refactor TestFsck. Contributed by Takanobu Asanuma.
| hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFsck.java | HDFS-10933. Refactor TestFsck. Contributed by Takanobu Asanuma. | <ide><path>adoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFsck.java
<ide> import java.util.regex.Pattern;
<ide>
<ide> import com.google.common.base.Supplier;
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<ide> import org.apache.commons.logging.impl.Log4JLogger;
<ide> import org.apache.hadoop.conf.Configuration;
<add>import org.apache.hadoop.fs.ChecksumException;
<ide> import org.apache.hadoop.fs.FSDataOutputStream;
<ide> import org.apache.hadoop.fs.FileContext;
<ide> import org.apache.hadoop.fs.FileSystem;
<ide> import org.apache.hadoop.hdfs.DFSTestUtil;
<ide> import org.apache.hadoop.hdfs.DFSUtil;
<ide> import org.apache.hadoop.hdfs.DistributedFileSystem;
<del>import org.apache.hadoop.hdfs.HdfsConfiguration;
<ide> import org.apache.hadoop.hdfs.MiniDFSCluster;
<ide> import org.apache.hadoop.fs.StorageType;
<ide> import org.apache.hadoop.hdfs.StripedFileTestUtil;
<ide> import org.apache.log4j.Logger;
<ide> import org.apache.log4j.PatternLayout;
<ide> import org.apache.log4j.RollingFileAppender;
<add>import org.junit.After;
<ide> import org.junit.Assert;
<add>import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<ide> import com.google.common.collect.Sets;
<ide>
<ide> /**
<del> * A JUnit test for doing fsck
<add> * A JUnit test for doing fsck.
<ide> */
<ide> public class TestFsck {
<add> private static final Log LOG =
<add> LogFactory.getLog(TestFsck.class.getName());
<add>
<ide> static final String AUDITLOG_FILE =
<ide> GenericTestUtils.getTempPath("TestFsck-audit.log");
<ide>
<ide> // Pattern for:
<ide> // allowed=true ugi=name ip=/address cmd=FSCK src=/ dst=null perm=null
<del> static final Pattern fsckPattern = Pattern.compile(
<add> static final Pattern FSCK_PATTERN = Pattern.compile(
<ide> "allowed=.*?\\s" +
<ide> "ugi=.*?\\s" +
<ide> "ip=/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\s" +
<ide> "cmd=fsck\\ssrc=\\/\\sdst=null\\s" +
<ide> "perm=null\\s" + "proto=.*");
<del> static final Pattern getfileinfoPattern = Pattern.compile(
<add> static final Pattern GET_FILE_INFO_PATTERN = Pattern.compile(
<ide> "allowed=.*?\\s" +
<ide> "ugi=.*?\\s" +
<ide> "ip=/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\s" +
<ide> "cmd=getfileinfo\\ssrc=\\/\\sdst=null\\s" +
<ide> "perm=null\\s" + "proto=.*");
<ide>
<del> static final Pattern numMissingBlocksPattern = Pattern.compile(
<add> static final Pattern NUM_MISSING_BLOCKS_PATTERN = Pattern.compile(
<ide> ".*Missing blocks:\t\t([0123456789]*).*");
<ide>
<del> static final Pattern numCorruptBlocksPattern = Pattern.compile(
<add> static final Pattern NUM_CORRUPT_BLOCKS_PATTERN = Pattern.compile(
<ide> ".*Corrupt blocks:\t\t([0123456789]*).*");
<ide>
<ide> private static final String LINE_SEPARATOR =
<del> System.getProperty("line.separator");
<add> System.getProperty("line.separator");
<ide>
<ide> static String runFsck(Configuration conf, int expectedErrCode,
<del> boolean checkErrorCode,String... path)
<add> boolean checkErrorCode, String... path)
<ide> throws Exception {
<ide> ByteArrayOutputStream bStream = new ByteArrayOutputStream();
<ide> PrintStream out = new PrintStream(bStream, true);
<ide> assertEquals(expectedErrCode, errCode);
<ide> }
<ide> GenericTestUtils.setLogLevel(FSPermissionChecker.LOG, Level.INFO);
<del> FSImage.LOG.info("OUTPUT = " + bStream.toString());
<add> LOG.info("OUTPUT = " + bStream.toString());
<ide> return bStream.toString();
<ide> }
<ide>
<del> /** do fsck */
<add> private MiniDFSCluster cluster = null;
<add> private Configuration conf = null;
<add>
<add> @Before
<add> public void setUp() throws Exception {
<add> conf = new Configuration();
<add> }
<add>
<add> @After
<add> public void tearDown() throws Exception {
<add> shutdownCluster();
<add> }
<add>
<add> private void shutdownCluster() throws Exception {
<add> if (cluster != null) {
<add> cluster.shutdown();
<add> }
<add> }
<add>
<add> /** do fsck. */
<ide> @Test
<ide> public void testFsck() throws Exception {
<ide> DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck").
<ide> setNumFiles(20).build();
<del> MiniDFSCluster cluster = null;
<ide> FileSystem fs = null;
<del> try {
<del> Configuration conf = new HdfsConfiguration();
<del> final long precision = 1L;
<del> conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, precision);
<del> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<del> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<del> fs = cluster.getFileSystem();
<del> final String fileName = "/srcdat";
<del> util.createFiles(fs, fileName);
<del> util.waitReplication(fs, fileName, (short)3);
<del> final Path file = new Path(fileName);
<del> long aTime = fs.getFileStatus(file).getAccessTime();
<del> Thread.sleep(precision);
<del> setupAuditLogs();
<del> String outStr = runFsck(conf, 0, true, "/");
<del> verifyAuditLogs();
<del> assertEquals(aTime, fs.getFileStatus(file).getAccessTime());
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> cluster.shutdown();
<del>
<del> // restart the cluster; bring up namenode but not the data nodes
<del> cluster = new MiniDFSCluster.Builder(conf)
<del> .numDataNodes(0).format(false).build();
<del> outStr = runFsck(conf, 1, true, "/");
<del> // expect the result is corrupt
<del> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<del> System.out.println(outStr);
<del>
<del> // bring up data nodes & cleanup cluster
<del> cluster.startDataNodes(conf, 4, true, null, null);
<del> cluster.waitActive();
<del> cluster.waitClusterUp();
<del> fs = cluster.getFileSystem();
<del> util.cleanup(fs, "/srcdat");
<del> } finally {
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> if (cluster != null) { cluster.shutdown(); }
<del> }
<del> }
<del>
<del> /** Sets up log4j logger for auditlogs */
<add> final long precision = 1L;
<add> conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY,
<add> precision);
<add> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<add> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<add> fs = cluster.getFileSystem();
<add> final String fileName = "/srcdat";
<add> util.createFiles(fs, fileName);
<add> util.waitReplication(fs, fileName, (short)3);
<add> final Path file = new Path(fileName);
<add> long aTime = fs.getFileStatus(file).getAccessTime();
<add> Thread.sleep(precision);
<add> setupAuditLogs();
<add> String outStr = runFsck(conf, 0, true, "/");
<add> verifyAuditLogs();
<add> assertEquals(aTime, fs.getFileStatus(file).getAccessTime());
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> shutdownCluster();
<add>
<add> // restart the cluster; bring up namenode but not the data nodes
<add> cluster = new MiniDFSCluster.Builder(conf)
<add> .numDataNodes(0).format(false).build();
<add> outStr = runFsck(conf, 1, true, "/");
<add> // expect the result is corrupt
<add> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<add> System.out.println(outStr);
<add>
<add> // bring up data nodes & cleanup cluster
<add> cluster.startDataNodes(conf, 4, true, null, null);
<add> cluster.waitActive();
<add> cluster.waitClusterUp();
<add> fs = cluster.getFileSystem();
<add> util.cleanup(fs, "/srcdat");
<add> }
<add>
<add> /** Sets up log4j logger for auditlogs. */
<ide> private void setupAuditLogs() throws IOException {
<ide> File file = new File(AUDITLOG_FILE);
<ide> if (file.exists()) {
<ide> line = reader.readLine();
<ide> assertNotNull(line);
<ide> assertTrue("Expected getfileinfo event not found in audit log",
<del> getfileinfoPattern.matcher(line).matches());
<add> GET_FILE_INFO_PATTERN.matcher(line).matches());
<ide> }
<ide> line = reader.readLine();
<ide> assertNotNull(line);
<del> assertTrue("Expected fsck event not found in audit log", fsckPattern
<add> assertTrue("Expected fsck event not found in audit log", FSCK_PATTERN
<ide> .matcher(line).matches());
<ide> assertNull("Unexpected event in audit log", reader.readLine());
<ide> } finally {
<ide> public void testFsckNonExistent() throws Exception {
<ide> DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck").
<ide> setNumFiles(20).build();
<del> MiniDFSCluster cluster = null;
<ide> FileSystem fs = null;
<del> try {
<del> Configuration conf = new HdfsConfiguration();
<del> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<del> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<del> fs = cluster.getFileSystem();
<del> util.createFiles(fs, "/srcdat");
<del> util.waitReplication(fs, "/srcdat", (short)3);
<del> String outStr = runFsck(conf, 0, true, "/non-existent");
<del> assertEquals(-1, outStr.indexOf(NamenodeFsck.HEALTHY_STATUS));
<del> System.out.println(outStr);
<del> util.cleanup(fs, "/srcdat");
<del> } finally {
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> if (cluster != null) { cluster.shutdown(); }
<del> }
<del> }
<del>
<del> /** Test fsck with permission set on inodes */
<add> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<add> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<add> fs = cluster.getFileSystem();
<add> util.createFiles(fs, "/srcdat");
<add> util.waitReplication(fs, "/srcdat", (short)3);
<add> String outStr = runFsck(conf, 0, true, "/non-existent");
<add> assertEquals(-1, outStr.indexOf(NamenodeFsck.HEALTHY_STATUS));
<add> System.out.println(outStr);
<add> util.cleanup(fs, "/srcdat");
<add> }
<add>
<add> /** Test fsck with permission set on inodes. */
<ide> @Test
<ide> public void testFsckPermission() throws Exception {
<ide> final DFSTestUtil util = new DFSTestUtil.Builder().
<ide> setName(getClass().getSimpleName()).setNumFiles(20).build();
<del> final Configuration conf = new HdfsConfiguration();
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<ide>
<del> MiniDFSCluster cluster = null;
<del> try {
<del> // Create a cluster with the current user, write some files
<del> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<del> final MiniDFSCluster c2 = cluster;
<del> final String dir = "/dfsck";
<del> final Path dirpath = new Path(dir);
<del> final FileSystem fs = c2.getFileSystem();
<del>
<del> util.createFiles(fs, dir);
<del> util.waitReplication(fs, dir, (short) 3);
<del> fs.setPermission(dirpath, new FsPermission((short) 0700));
<del>
<del> // run DFSck as another user, should fail with permission issue
<del> UserGroupInformation fakeUGI = UserGroupInformation.createUserForTesting(
<del> "ProbablyNotARealUserName", new String[] { "ShangriLa" });
<del> fakeUGI.doAs(new PrivilegedExceptionAction<Object>() {
<del> @Override
<del> public Object run() throws Exception {
<del> System.out.println(runFsck(conf, -1, true, dir));
<del> return null;
<del> }
<del> });
<del>
<del> // set permission and try DFSck again as the fake user, should succeed
<del> fs.setPermission(dirpath, new FsPermission((short) 0777));
<del> fakeUGI.doAs(new PrivilegedExceptionAction<Object>() {
<del> @Override
<del> public Object run() throws Exception {
<del> final String outStr = runFsck(conf, 0, true, dir);
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> return null;
<del> }
<del> });
<del>
<del> util.cleanup(fs, dir);
<del> } finally {
<del> if (cluster != null) { cluster.shutdown(); }
<del> }
<add> // Create a cluster with the current user, write some files
<add> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<add> final MiniDFSCluster c2 = cluster;
<add> final String dir = "/dfsck";
<add> final Path dirpath = new Path(dir);
<add> final FileSystem fs = c2.getFileSystem();
<add>
<add> util.createFiles(fs, dir);
<add> util.waitReplication(fs, dir, (short) 3);
<add> fs.setPermission(dirpath, new FsPermission((short) 0700));
<add>
<add> // run DFSck as another user, should fail with permission issue
<add> UserGroupInformation fakeUGI = UserGroupInformation.createUserForTesting(
<add> "ProbablyNotARealUserName", new String[] {"ShangriLa"});
<add> fakeUGI.doAs(new PrivilegedExceptionAction<Object>() {
<add> @Override
<add> public Object run() throws Exception {
<add> System.out.println(runFsck(conf, -1, true, dir));
<add> return null;
<add> }
<add> });
<add>
<add> // set permission and try DFSck again as the fake user, should succeed
<add> fs.setPermission(dirpath, new FsPermission((short) 0777));
<add> fakeUGI.doAs(new PrivilegedExceptionAction<Object>() {
<add> @Override
<add> public Object run() throws Exception {
<add> final String outStr = runFsck(conf, 0, true, dir);
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> return null;
<add> }
<add> });
<add>
<add> util.cleanup(fs, dir);
<ide> }
<ide>
<ide> @Test
<ide> public void testFsckMove() throws Exception {
<del> Configuration conf = new HdfsConfiguration();
<del> final int DFS_BLOCK_SIZE = 1024;
<del> final int NUM_DATANODES = 4;
<del> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DFS_BLOCK_SIZE);
<add> final int dfsBlockSize = 1024;
<add> final int numDatanodes = 4;
<add> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, dfsBlockSize);
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<ide> conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
<ide> DFSTestUtil util = new DFSTestUtil("TestFsck", 5, 3,
<del> (5 * DFS_BLOCK_SIZE) + (DFS_BLOCK_SIZE - 1), 5 * DFS_BLOCK_SIZE);
<del> MiniDFSCluster cluster = null;
<add> (5 * dfsBlockSize) + (dfsBlockSize - 1), 5 * dfsBlockSize);
<ide> FileSystem fs = null;
<del> try {
<del> cluster = new MiniDFSCluster.Builder(conf).
<del> numDataNodes(NUM_DATANODES).build();
<del> String topDir = "/srcdat";
<del> fs = cluster.getFileSystem();
<del> cluster.waitActive();
<del> util.createFiles(fs, topDir);
<del> util.waitReplication(fs, topDir, (short)3);
<del> String outStr = runFsck(conf, 0, true, "/");
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> DFSClient dfsClient = new DFSClient(new InetSocketAddress("localhost",
<del> cluster.getNameNodePort()), conf);
<del> String fileNames[] = util.getFileNames(topDir);
<del> CorruptedTestFile ctFiles[] = new CorruptedTestFile[] {
<add> cluster = new MiniDFSCluster.Builder(conf).
<add> numDataNodes(numDatanodes).build();
<add> String topDir = "/srcdat";
<add> fs = cluster.getFileSystem();
<add> cluster.waitActive();
<add> util.createFiles(fs, topDir);
<add> util.waitReplication(fs, topDir, (short)3);
<add> String outStr = runFsck(conf, 0, true, "/");
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> DFSClient dfsClient = new DFSClient(new InetSocketAddress("localhost",
<add> cluster.getNameNodePort()), conf);
<add> String[] fileNames = util.getFileNames(topDir);
<add> CorruptedTestFile[] ctFiles = new CorruptedTestFile[]{
<ide> new CorruptedTestFile(fileNames[0], Sets.newHashSet(0),
<del> dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE),
<add> dfsClient, numDatanodes, dfsBlockSize),
<ide> new CorruptedTestFile(fileNames[1], Sets.newHashSet(2, 3),
<del> dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE),
<add> dfsClient, numDatanodes, dfsBlockSize),
<ide> new CorruptedTestFile(fileNames[2], Sets.newHashSet(4),
<del> dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE),
<add> dfsClient, numDatanodes, dfsBlockSize),
<ide> new CorruptedTestFile(fileNames[3], Sets.newHashSet(0, 1, 2, 3),
<del> dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE),
<add> dfsClient, numDatanodes, dfsBlockSize),
<ide> new CorruptedTestFile(fileNames[4], Sets.newHashSet(1, 2, 3, 4),
<del> dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE)
<del> };
<del> int totalMissingBlocks = 0;
<del> for (CorruptedTestFile ctFile : ctFiles) {
<del> totalMissingBlocks += ctFile.getTotalMissingBlocks();
<del> }
<del> for (CorruptedTestFile ctFile : ctFiles) {
<del> ctFile.removeBlocks(cluster);
<del> }
<del> // Wait for fsck to discover all the missing blocks
<del> while (true) {
<del> outStr = runFsck(conf, 1, false, "/");
<del> String numMissing = null;
<del> String numCorrupt = null;
<del> for (String line : outStr.split(LINE_SEPARATOR)) {
<del> Matcher m = numMissingBlocksPattern.matcher(line);
<del> if (m.matches()) {
<del> numMissing = m.group(1);
<del> }
<del> m = numCorruptBlocksPattern.matcher(line);
<del> if (m.matches()) {
<del> numCorrupt = m.group(1);
<del> }
<del> if (numMissing != null && numCorrupt != null) {
<del> break;
<del> }
<add> dfsClient, numDatanodes, dfsBlockSize)
<add> };
<add> int totalMissingBlocks = 0;
<add> for (CorruptedTestFile ctFile : ctFiles) {
<add> totalMissingBlocks += ctFile.getTotalMissingBlocks();
<add> }
<add> for (CorruptedTestFile ctFile : ctFiles) {
<add> ctFile.removeBlocks(cluster);
<add> }
<add> // Wait for fsck to discover all the missing blocks
<add> while (true) {
<add> outStr = runFsck(conf, 1, false, "/");
<add> String numMissing = null;
<add> String numCorrupt = null;
<add> for (String line : outStr.split(LINE_SEPARATOR)) {
<add> Matcher m = NUM_MISSING_BLOCKS_PATTERN.matcher(line);
<add> if (m.matches()) {
<add> numMissing = m.group(1);
<ide> }
<del> if (numMissing == null || numCorrupt == null) {
<del> throw new IOException("failed to find number of missing or corrupt" +
<del> " blocks in fsck output.");
<add> m = NUM_CORRUPT_BLOCKS_PATTERN.matcher(line);
<add> if (m.matches()) {
<add> numCorrupt = m.group(1);
<ide> }
<del> if (numMissing.equals(Integer.toString(totalMissingBlocks))) {
<del> assertTrue(numCorrupt.equals(Integer.toString(0)));
<del> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<add> if (numMissing != null && numCorrupt != null) {
<ide> break;
<ide> }
<del> try {
<del> Thread.sleep(100);
<del> } catch (InterruptedException ignore) {
<del> }
<del> }
<del>
<del> // Copy the non-corrupt blocks of corruptFileName to lost+found.
<del> outStr = runFsck(conf, 1, false, "/", "-move");
<del> FSImage.LOG.info("WATERMELON: outStr = " + outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<del>
<del> // Make sure that we properly copied the block files from the DataNodes
<del> // to lost+found
<del> for (CorruptedTestFile ctFile : ctFiles) {
<del> ctFile.checkSalvagedRemains();
<del> }
<del>
<del> // Fix the filesystem by removing corruptFileName
<del> outStr = runFsck(conf, 1, true, "/", "-delete");
<del> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<del>
<del> // Check to make sure we have a healthy filesystem
<del> outStr = runFsck(conf, 0, true, "/");
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> util.cleanup(fs, topDir);
<del> } finally {
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> if (cluster != null) { cluster.shutdown(); }
<del> }
<add> }
<add> if (numMissing == null || numCorrupt == null) {
<add> throw new IOException("failed to find number of missing or corrupt" +
<add> " blocks in fsck output.");
<add> }
<add> if (numMissing.equals(Integer.toString(totalMissingBlocks))) {
<add> assertTrue(numCorrupt.equals(Integer.toString(0)));
<add> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<add> break;
<add> }
<add> try {
<add> Thread.sleep(100);
<add> } catch (InterruptedException ignore) {
<add> }
<add> }
<add>
<add> // Copy the non-corrupt blocks of corruptFileName to lost+found.
<add> outStr = runFsck(conf, 1, false, "/", "-move");
<add> LOG.info("WATERMELON: outStr = " + outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<add>
<add> // Make sure that we properly copied the block files from the DataNodes
<add> // to lost+found
<add> for (CorruptedTestFile ctFile : ctFiles) {
<add> ctFile.checkSalvagedRemains();
<add> }
<add>
<add> // Fix the filesystem by removing corruptFileName
<add> outStr = runFsck(conf, 1, true, "/", "-delete");
<add> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<add>
<add> // Check to make sure we have a healthy filesystem
<add> outStr = runFsck(conf, 0, true, "/");
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> util.cleanup(fs, topDir);
<ide> }
<ide>
<ide> static private class CorruptedTestFile {
<ide> final private int blockSize;
<ide> final private byte[] initialContents;
<ide>
<del> public CorruptedTestFile(String name, Set<Integer> blocksToCorrupt,
<add> CorruptedTestFile(String name, Set<Integer> blocksToCorrupt,
<ide> DFSClient dfsClient, int numDataNodes, int blockSize)
<ide> throws IOException {
<ide> this.name = name;
<ide> new FileOutputStream(blockFile, false);
<ide> blockFileStream.write("corrupt".getBytes());
<ide> blockFileStream.close();
<del> FSImage.LOG.info("Corrupted block file " + blockFile);
<add> LOG.info("Corrupted block file " + blockFile);
<ide> }
<ide> }
<ide> }
<ide> if (blockIdx == (numBlocks - 1)) {
<ide> // The last block might not be full-length
<ide> len = (int)(in.getFileLength() % blockSize);
<del> if (len == 0) len = blockBuffer.length;
<add> if (len == 0) {
<add> len = blockBuffer.length;
<add> }
<ide> }
<ide> IOUtils.readFully(in, blockBuffer, 0, len);
<ide> int startIdx = blockIdx * blockSize;
<ide>
<ide> @Test
<ide> public void testFsckMoveAndDelete() throws Exception {
<del> final int MAX_MOVE_TRIES = 5;
<add> final int maxMoveTries = 5;
<ide> DFSTestUtil util = new DFSTestUtil.Builder().
<ide> setName("TestFsckMoveAndDelete").setNumFiles(5).build();
<del> MiniDFSCluster cluster = null;
<ide> FileSystem fs = null;
<del> try {
<del> Configuration conf = new HdfsConfiguration();
<del> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<del> conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
<del> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<del> String topDir = "/srcdat";
<del> fs = cluster.getFileSystem();
<del> cluster.waitActive();
<del> util.createFiles(fs, topDir);
<del> util.waitReplication(fs, topDir, (short)3);
<del> String outStr = runFsck(conf, 0, true, "/");
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del>
<del> // Corrupt a block by deleting it
<del> String[] fileNames = util.getFileNames(topDir);
<del> DFSClient dfsClient = new DFSClient(new InetSocketAddress("localhost",
<del> cluster.getNameNodePort()), conf);
<del> String corruptFileName = fileNames[0];
<del> ExtendedBlock block = dfsClient.getNamenode().getBlockLocations(
<del> corruptFileName, 0, Long.MAX_VALUE).get(0).getBlock();
<del> for (int i=0; i<4; i++) {
<del> File blockFile = cluster.getBlockFile(i, block);
<del> if(blockFile != null && blockFile.exists()) {
<del> assertTrue(blockFile.delete());
<add> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<add> conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
<add> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<add> String topDir = "/srcdat";
<add> fs = cluster.getFileSystem();
<add> cluster.waitActive();
<add> util.createFiles(fs, topDir);
<add> util.waitReplication(fs, topDir, (short)3);
<add> String outStr = runFsck(conf, 0, true, "/");
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add>
<add> // Corrupt a block by deleting it
<add> String[] fileNames = util.getFileNames(topDir);
<add> DFSClient dfsClient = new DFSClient(new InetSocketAddress("localhost",
<add> cluster.getNameNodePort()), conf);
<add> String corruptFileName = fileNames[0];
<add> ExtendedBlock block = dfsClient.getNamenode().getBlockLocations(
<add> corruptFileName, 0, Long.MAX_VALUE).get(0).getBlock();
<add> for (int i=0; i<4; i++) {
<add> File blockFile = cluster.getBlockFile(i, block);
<add> if(blockFile != null && blockFile.exists()) {
<add> assertTrue(blockFile.delete());
<add> }
<add> }
<add>
<add> // We excpect the filesystem to be corrupted
<add> outStr = runFsck(conf, 1, false, "/");
<add> while (!outStr.contains(NamenodeFsck.CORRUPT_STATUS)) {
<add> try {
<add> Thread.sleep(100);
<add> } catch (InterruptedException ignore) {
<add> }
<add> outStr = runFsck(conf, 1, false, "/");
<add> }
<add>
<add> // After a fsck -move, the corrupted file should still exist.
<add> for (int i = 0; i < maxMoveTries; i++) {
<add> outStr = runFsck(conf, 1, true, "/", "-move");
<add> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<add> String[] newFileNames = util.getFileNames(topDir);
<add> boolean found = false;
<add> for (String f : newFileNames) {
<add> if (f.equals(corruptFileName)) {
<add> found = true;
<add> break;
<ide> }
<ide> }
<del>
<del> // We excpect the filesystem to be corrupted
<del> outStr = runFsck(conf, 1, false, "/");
<del> while (!outStr.contains(NamenodeFsck.CORRUPT_STATUS)) {
<del> try {
<del> Thread.sleep(100);
<del> } catch (InterruptedException ignore) {
<del> }
<del> outStr = runFsck(conf, 1, false, "/");
<del> }
<del>
<del> // After a fsck -move, the corrupted file should still exist.
<del> for (int i = 0; i < MAX_MOVE_TRIES; i++) {
<del> outStr = runFsck(conf, 1, true, "/", "-move" );
<del> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<del> String[] newFileNames = util.getFileNames(topDir);
<del> boolean found = false;
<del> for (String f : newFileNames) {
<del> if (f.equals(corruptFileName)) {
<del> found = true;
<del> break;
<del> }
<del> }
<del> assertTrue(found);
<del> }
<del>
<del> // Fix the filesystem by moving corrupted files to lost+found
<del> outStr = runFsck(conf, 1, true, "/", "-move", "-delete");
<del> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<del>
<del> // Check to make sure we have healthy filesystem
<del> outStr = runFsck(conf, 0, true, "/");
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> util.cleanup(fs, topDir);
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> cluster.shutdown();
<del> } finally {
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> if (cluster != null) { cluster.shutdown(); }
<del> }
<add> assertTrue(found);
<add> }
<add>
<add> // Fix the filesystem by moving corrupted files to lost+found
<add> outStr = runFsck(conf, 1, true, "/", "-move", "-delete");
<add> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<add>
<add> // Check to make sure we have healthy filesystem
<add> outStr = runFsck(conf, 0, true, "/");
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> util.cleanup(fs, topDir);
<ide> }
<ide>
<ide> @Test
<ide> public void testFsckOpenFiles() throws Exception {
<ide> DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck").
<ide> setNumFiles(4).build();
<del> MiniDFSCluster cluster = null;
<ide> FileSystem fs = null;
<del> try {
<del> Configuration conf = new HdfsConfiguration();
<del> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<del> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<del> String topDir = "/srcdat";
<del> String randomString = "HADOOP ";
<del> fs = cluster.getFileSystem();
<del> cluster.waitActive();
<del> util.createFiles(fs, topDir);
<del> util.waitReplication(fs, topDir, (short)3);
<del> String outStr = runFsck(conf, 0, true, "/");
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> // Open a file for writing and do not close for now
<del> Path openFile = new Path(topDir + "/openFile");
<del> FSDataOutputStream out = fs.create(openFile);
<del> int writeCount = 0;
<del> while (writeCount != 100) {
<del> out.write(randomString.getBytes());
<del> writeCount++;
<del> }
<del> ((DFSOutputStream) out.getWrappedStream()).hflush();
<del> // We expect the filesystem to be HEALTHY and show one open file
<del> outStr = runFsck(conf, 0, true, topDir);
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> assertFalse(outStr.contains("OPENFORWRITE"));
<del> // Use -openforwrite option to list open files
<del> outStr = runFsck(conf, 0, true, topDir, "-files", "-blocks",
<del> "-locations", "-openforwrite");
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains("OPENFORWRITE"));
<del> assertTrue(outStr.contains("Under Construction Block:"));
<del> assertTrue(outStr.contains("openFile"));
<del> // Close the file
<del> out.close();
<del> // Now, fsck should show HEALTHY fs and should not show any open files
<del> outStr = runFsck(conf, 0, true, topDir);
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> assertFalse(outStr.contains("OPENFORWRITE"));
<del> assertFalse(outStr.contains("Under Construction Block:"));
<del> util.cleanup(fs, topDir);
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> cluster.shutdown();
<del> } finally {
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> if (cluster != null) { cluster.shutdown(); }
<del> }
<add> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<add> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<add> String topDir = "/srcdat";
<add> String randomString = "HADOOP ";
<add> fs = cluster.getFileSystem();
<add> cluster.waitActive();
<add> util.createFiles(fs, topDir);
<add> util.waitReplication(fs, topDir, (short)3);
<add> String outStr = runFsck(conf, 0, true, "/");
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> // Open a file for writing and do not close for now
<add> Path openFile = new Path(topDir + "/openFile");
<add> FSDataOutputStream out = fs.create(openFile);
<add> int writeCount = 0;
<add> while (writeCount != 100) {
<add> out.write(randomString.getBytes());
<add> writeCount++;
<add> }
<add> ((DFSOutputStream) out.getWrappedStream()).hflush();
<add> // We expect the filesystem to be HEALTHY and show one open file
<add> outStr = runFsck(conf, 0, true, topDir);
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> assertFalse(outStr.contains("OPENFORWRITE"));
<add> // Use -openforwrite option to list open files
<add> outStr = runFsck(conf, 0, true, topDir, "-files", "-blocks",
<add> "-locations", "-openforwrite");
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains("OPENFORWRITE"));
<add> assertTrue(outStr.contains("Under Construction Block:"));
<add> assertTrue(outStr.contains("openFile"));
<add> // Close the file
<add> out.close();
<add> // Now, fsck should show HEALTHY fs and should not show any open files
<add> outStr = runFsck(conf, 0, true, topDir);
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> assertFalse(outStr.contains("OPENFORWRITE"));
<add> assertFalse(outStr.contains("Under Construction Block:"));
<add> util.cleanup(fs, topDir);
<ide> }
<ide>
<ide> @Test
<ide> public void testFsckOpenECFiles() throws Exception {
<ide> DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsckECFile").
<ide> setNumFiles(4).build();
<del> Configuration conf = new HdfsConfiguration();
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<ide> ErasureCodingPolicy ecPolicy =
<ide> ErasureCodingPolicyManager.getSystemDefaultPolicy();
<ide> int numAllUnits = ecPolicy.getNumDataUnits() + ecPolicy.getNumParityUnits();
<del> MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(
<add> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(
<ide> numAllUnits + 1).build();
<ide> FileSystem fs = null;
<del> try {
<del> String topDir = "/myDir";
<del> byte[] randomBytes = new byte[3000000];
<del> int seed = 42;
<del> new Random(seed).nextBytes(randomBytes);
<del> cluster.waitActive();
<del> fs = cluster.getFileSystem();
<del> util.createFiles(fs, topDir);
<del> // set topDir to EC when it has replicated files
<del> cluster.getFileSystem().getClient().setErasureCodingPolicy(
<del> topDir, ecPolicy);
<del>
<del> // create a new file under topDir
<del> DFSTestUtil.createFile(fs, new Path(topDir, "ecFile"), 1024, (short) 1, 0L);
<del> // Open a EC file for writing and do not close for now
<del> Path openFile = new Path(topDir + "/openECFile");
<del> FSDataOutputStream out = fs.create(openFile);
<del> int writeCount = 0;
<del> while (writeCount != 300) {
<del> out.write(randomBytes);
<del> writeCount++;
<del> }
<del>
<del> // make sure the fsck can correctly handle mixed ec/replicated files
<del> runFsck(conf, 0, true, topDir, "-files", "-blocks", "-openforwrite");
<del>
<del> // We expect the filesystem to be HEALTHY and show one open file
<del> String outStr = runFsck(conf, 0, true, openFile.toString(), "-files",
<del> "-blocks", "-openforwrite");
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> assertTrue(outStr.contains("OPENFORWRITE"));
<del> assertTrue(outStr.contains("Live_repl=" + numAllUnits));
<del> assertTrue(outStr.contains("Expected_repl=" + numAllUnits));
<del>
<del> // Use -openforwrite option to list open files
<del> outStr = runFsck(conf, 0, true, openFile.toString(), "-files", "-blocks",
<del> "-locations", "-openforwrite", "-replicaDetails");
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> assertTrue(outStr.contains("OPENFORWRITE"));
<del> assertTrue(outStr.contains("Live_repl=" + numAllUnits));
<del> assertTrue(outStr.contains("Expected_repl=" + numAllUnits));
<del> assertTrue(outStr.contains("Under Construction Block:"));
<del>
<del> // Close the file
<del> out.close();
<del>
<del> // Now, fsck should show HEALTHY fs and should not show any open files
<del> outStr = runFsck(conf, 0, true, openFile.toString(), "-files", "-blocks",
<del> "-locations", "-racks", "-replicaDetails");
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> assertFalse(outStr.contains("OPENFORWRITE"));
<del> assertFalse(outStr.contains("Under Construction Block:"));
<del> assertFalse(outStr.contains("Expected_repl=" + numAllUnits));
<del> assertTrue(outStr.contains("Live_repl=" + numAllUnits));
<del> util.cleanup(fs, topDir);
<del> } finally {
<del> if (fs != null) {
<del> try {
<del> fs.close();
<del> } catch (Exception e) {
<del> }
<del> }
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<add> String topDir = "/myDir";
<add> byte[] randomBytes = new byte[3000000];
<add> int seed = 42;
<add> new Random(seed).nextBytes(randomBytes);
<add> cluster.waitActive();
<add> fs = cluster.getFileSystem();
<add> util.createFiles(fs, topDir);
<add> // set topDir to EC when it has replicated files
<add> cluster.getFileSystem().getClient().setErasureCodingPolicy(
<add> topDir, ecPolicy);
<add>
<add> // create a new file under topDir
<add> DFSTestUtil.createFile(fs, new Path(topDir, "ecFile"), 1024, (short) 1, 0L);
<add> // Open a EC file for writing and do not close for now
<add> Path openFile = new Path(topDir + "/openECFile");
<add> FSDataOutputStream out = fs.create(openFile);
<add> int writeCount = 0;
<add> while (writeCount != 300) {
<add> out.write(randomBytes);
<add> writeCount++;
<add> }
<add>
<add> // make sure the fsck can correctly handle mixed ec/replicated files
<add> runFsck(conf, 0, true, topDir, "-files", "-blocks", "-openforwrite");
<add>
<add> // We expect the filesystem to be HEALTHY and show one open file
<add> String outStr = runFsck(conf, 0, true, openFile.toString(), "-files",
<add> "-blocks", "-openforwrite");
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> assertTrue(outStr.contains("OPENFORWRITE"));
<add> assertTrue(outStr.contains("Live_repl=" + numAllUnits));
<add> assertTrue(outStr.contains("Expected_repl=" + numAllUnits));
<add>
<add> // Use -openforwrite option to list open files
<add> outStr = runFsck(conf, 0, true, openFile.toString(), "-files", "-blocks",
<add> "-locations", "-openforwrite", "-replicaDetails");
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> assertTrue(outStr.contains("OPENFORWRITE"));
<add> assertTrue(outStr.contains("Live_repl=" + numAllUnits));
<add> assertTrue(outStr.contains("Expected_repl=" + numAllUnits));
<add> assertTrue(outStr.contains("Under Construction Block:"));
<add>
<add> // Close the file
<add> out.close();
<add>
<add> // Now, fsck should show HEALTHY fs and should not show any open files
<add> outStr = runFsck(conf, 0, true, openFile.toString(), "-files", "-blocks",
<add> "-locations", "-racks", "-replicaDetails");
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> assertFalse(outStr.contains("OPENFORWRITE"));
<add> assertFalse(outStr.contains("Under Construction Block:"));
<add> assertFalse(outStr.contains("Expected_repl=" + numAllUnits));
<add> assertTrue(outStr.contains("Live_repl=" + numAllUnits));
<add> util.cleanup(fs, topDir);
<ide> }
<ide>
<ide> @Test
<ide> public void testCorruptBlock() throws Exception {
<del> Configuration conf = new HdfsConfiguration();
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
<ide> // Set short retry timeouts so this test runs faster
<ide> conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10);
<ide> String outStr = null;
<ide> short factor = 1;
<ide>
<del> MiniDFSCluster cluster = null;
<del> try {
<ide> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
<ide> cluster.waitActive();
<ide> fs = cluster.getFileSystem();
<ide> IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(), conf,
<ide> true);
<ide> } catch (IOException ie) {
<del> // Ignore exception
<add> assertTrue(ie instanceof ChecksumException);
<ide> }
<ide>
<ide> dfsClient = new DFSClient(new InetSocketAddress("localhost",
<ide> getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
<ide> replicaCount = blocks.get(0).getLocations().length;
<ide> }
<del> assertTrue (blocks.get(0).isCorrupt());
<add> assertTrue(blocks.get(0).isCorrupt());
<ide>
<ide> // Check if fsck reports the same
<ide> outStr = runFsck(conf, 1, true, "/");
<ide> System.out.println(outStr);
<ide> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<ide> assertTrue(outStr.contains("testCorruptBlock"));
<del> } finally {
<del> if (cluster != null) {cluster.shutdown();}
<del> }
<ide> }
<ide>
<ide> @Test
<ide> public void testUnderMinReplicatedBlock() throws Exception {
<del> Configuration conf = new HdfsConfiguration();
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
<ide> // Set short retry timeouts so this test runs faster
<ide> conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10);
<ide> // Set minReplication to 2
<ide> short minReplication=2;
<del> conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY,minReplication);
<add> conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, minReplication);
<ide> FileSystem fs = null;
<ide> DFSClient dfsClient = null;
<ide> LocatedBlocks blocks = null;
<ide> Random random = new Random();
<ide> String outStr = null;
<ide> short factor = 1;
<del> MiniDFSCluster cluster = null;
<del> try {
<del> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
<del> cluster.waitActive();
<del> fs = cluster.getFileSystem();
<del> Path file1 = new Path("/testUnderMinReplicatedBlock");
<del> DFSTestUtil.createFile(fs, file1, 1024, minReplication, 0);
<del> // Wait until file replication has completed
<del> DFSTestUtil.waitReplication(fs, file1, minReplication);
<del> ExtendedBlock block = DFSTestUtil.getFirstBlock(fs, file1);
<del>
<del> // Make sure filesystem is in healthy state
<del> outStr = runFsck(conf, 0, true, "/");
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del>
<del> // corrupt the first replica
<del> File blockFile = cluster.getBlockFile(0, block);
<del> if (blockFile != null && blockFile.exists()) {
<del> RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
<del> FileChannel channel = raFile.getChannel();
<del> String badString = "BADBAD";
<del> int rand = random.nextInt((int) channel.size()/2);
<del> raFile.seek(rand);
<del> raFile.write(badString.getBytes());
<del> raFile.close();
<del> }
<del>
<del> dfsClient = new DFSClient(new InetSocketAddress("localhost",
<del> cluster.getNameNodePort()), conf);
<add> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
<add> cluster.waitActive();
<add> fs = cluster.getFileSystem();
<add> Path file1 = new Path("/testUnderMinReplicatedBlock");
<add> DFSTestUtil.createFile(fs, file1, 1024, minReplication, 0);
<add> // Wait until file replication has completed
<add> DFSTestUtil.waitReplication(fs, file1, minReplication);
<add> ExtendedBlock block = DFSTestUtil.getFirstBlock(fs, file1);
<add>
<add> // Make sure filesystem is in healthy state
<add> outStr = runFsck(conf, 0, true, "/");
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add>
<add> // corrupt the first replica
<add> File blockFile = cluster.getBlockFile(0, block);
<add> if (blockFile != null && blockFile.exists()) {
<add> RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
<add> FileChannel channel = raFile.getChannel();
<add> String badString = "BADBAD";
<add> int rand = random.nextInt((int) channel.size()/2);
<add> raFile.seek(rand);
<add> raFile.write(badString.getBytes());
<add> raFile.close();
<add> }
<add>
<add> dfsClient = new DFSClient(new InetSocketAddress("localhost",
<add> cluster.getNameNodePort()), conf);
<add> blocks = dfsClient.getNamenode().
<add> getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
<add> replicaCount = blocks.get(0).getLocations().length;
<add> while (replicaCount != factor) {
<add> try {
<add> Thread.sleep(100);
<add> // Read the file to trigger reportBadBlocks
<add> try {
<add> IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(),
<add> conf, true);
<add> } catch (IOException ie) {
<add> assertTrue(ie instanceof ChecksumException);
<add> }
<add> System.out.println("sleep in try: replicaCount=" + replicaCount
<add> + " factor=" + factor);
<add> } catch (InterruptedException ignore) {
<add> }
<ide> blocks = dfsClient.getNamenode().
<ide> getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
<ide> replicaCount = blocks.get(0).getLocations().length;
<del> while (replicaCount != factor) {
<del> try {
<del> Thread.sleep(100);
<del> // Read the file to trigger reportBadBlocks
<del> try {
<del> IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(), conf,
<del> true);
<del> } catch (IOException ie) {
<del> // Ignore exception
<del> }
<del> System.out.println("sleep in try: replicaCount="+replicaCount+" factor="+factor);
<del> } catch (InterruptedException ignore) {
<del> }
<del> blocks = dfsClient.getNamenode().
<del> getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
<del> replicaCount = blocks.get(0).getLocations().length;
<del> }
<del>
<del> // Check if fsck reports the same
<del> outStr = runFsck(conf, 0, true, "/");
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> assertTrue(outStr.contains("UNDER MIN REPL'D BLOCKS:\t1 (100.0 %)"));
<del> assertTrue(outStr.contains("dfs.namenode.replication.min:\t2"));
<del> } finally {
<del> if (cluster != null) {cluster.shutdown();}
<del> }
<add> }
<add>
<add> // Check if fsck reports the same
<add> outStr = runFsck(conf, 0, true, "/");
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> assertTrue(outStr.contains("UNDER MIN REPL'D BLOCKS:\t1 (100.0 %)"));
<add> assertTrue(outStr.contains("dfs.namenode.replication.min:\t2"));
<ide> }
<ide>
<ide> @Test(timeout = 60000)
<ide> public void testFsckReplicaDetails() throws Exception {
<ide>
<del> final short REPL_FACTOR = 1;
<del> short NUM_DN = 1;
<add> final short replFactor = 1;
<add> short numDn = 1;
<ide> final long blockSize = 512;
<ide> final long fileSize = 1024;
<ide> boolean checkDecommissionInProgress = false;
<del> String[] racks = { "/rack1" };
<del> String[] hosts = { "host1" };
<del>
<del> Configuration conf = new Configuration();
<add> String[] racks = {"/rack1"};
<add> String[] hosts = {"host1"};
<add>
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
<ide> conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
<ide>
<del> MiniDFSCluster cluster;
<ide> DistributedFileSystem dfs;
<ide> cluster =
<del> new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts).racks(racks).build();
<add> new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
<add> .racks(racks).build();
<ide> cluster.waitClusterUp();
<ide> dfs = cluster.getFileSystem();
<ide>
<ide> // create files
<ide> final String testFile = new String("/testfile");
<ide> final Path path = new Path(testFile);
<del> DFSTestUtil.createFile(dfs, path, fileSize, REPL_FACTOR, 1000L);
<del> DFSTestUtil.waitReplication(dfs, path, REPL_FACTOR);
<add> DFSTestUtil.createFile(dfs, path, fileSize, replFactor, 1000L);
<add> DFSTestUtil.waitReplication(dfs, path, replFactor);
<add>
<add> // make sure datanode that has replica is fine before decommission
<add> String fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks",
<add> "-replicaDetails");
<add> assertTrue(fsckOut.contains(NamenodeFsck.HEALTHY_STATUS));
<add> assertTrue(fsckOut.contains("(LIVE)"));
<add>
<add> // decommission datanode
<add> ExtendedBlock eb = DFSTestUtil.getFirstBlock(dfs, path);
<add> FSNamesystem fsn = cluster.getNameNode().getNamesystem();
<add> BlockManager bm = fsn.getBlockManager();
<add> BlockCollection bc = null;
<ide> try {
<del> // make sure datanode that has replica is fine before decommission
<del> String fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks", "-replicaDetails");
<del> assertTrue(fsckOut.contains(NamenodeFsck.HEALTHY_STATUS));
<del> assertTrue(fsckOut.contains("(LIVE)"));
<del>
<del> // decommission datanode
<del> ExtendedBlock eb = DFSTestUtil.getFirstBlock(dfs, path);
<del> FSNamesystem fsn = cluster.getNameNode().getNamesystem();
<del> BlockManager bm = fsn.getBlockManager();
<del> BlockCollection bc = null;
<del> try {
<del> fsn.writeLock();
<del> BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
<del> bc = fsn.getBlockCollection(bi);
<del> } finally {
<del> fsn.writeUnlock();
<del> }
<del> DatanodeDescriptor dn = bc.getBlocks()[0]
<del> .getDatanode(0);
<del> bm.getDatanodeManager().getDecomManager().startDecommission(dn);
<del> String dnName = dn.getXferAddr();
<del>
<del> // check the replica status while decommissioning
<del> fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks", "-replicaDetails");
<del> assertTrue(fsckOut.contains("(DECOMMISSIONING)"));
<del>
<del> // Start 2nd Datanode and wait for decommission to start
<del> cluster.startDataNodes(conf, 1, true, null, null, null);
<del> DatanodeInfo datanodeInfo = null;
<del> do {
<del> Thread.sleep(2000);
<del> for (DatanodeInfo info : dfs.getDataNodeStats()) {
<del> if (dnName.equals(info.getXferAddr())) {
<del> datanodeInfo = info;
<del> }
<add> fsn.writeLock();
<add> BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
<add> bc = fsn.getBlockCollection(bi);
<add> } finally {
<add> fsn.writeUnlock();
<add> }
<add> DatanodeDescriptor dn = bc.getBlocks()[0]
<add> .getDatanode(0);
<add> bm.getDatanodeManager().getDecomManager().startDecommission(dn);
<add> String dnName = dn.getXferAddr();
<add>
<add> // check the replica status while decommissioning
<add> fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks",
<add> "-replicaDetails");
<add> assertTrue(fsckOut.contains("(DECOMMISSIONING)"));
<add>
<add> // Start 2nd Datanode and wait for decommission to start
<add> cluster.startDataNodes(conf, 1, true, null, null, null);
<add> DatanodeInfo datanodeInfo = null;
<add> do {
<add> Thread.sleep(2000);
<add> for (DatanodeInfo info : dfs.getDataNodeStats()) {
<add> if (dnName.equals(info.getXferAddr())) {
<add> datanodeInfo = info;
<ide> }
<del> if (!checkDecommissionInProgress && datanodeInfo != null
<del> && datanodeInfo.isDecommissionInProgress()) {
<del> checkDecommissionInProgress = true;
<del> }
<del> } while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
<del>
<del> // check the replica status after decommission is done
<del> fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks", "-replicaDetails");
<del> assertTrue(fsckOut.contains("(DECOMMISSIONED)"));
<del> } finally {
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<del> }
<del>
<del> /** Test if fsck can return -1 in case of failure
<add> }
<add> if (!checkDecommissionInProgress && datanodeInfo != null
<add> && datanodeInfo.isDecommissionInProgress()) {
<add> checkDecommissionInProgress = true;
<add> }
<add> } while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
<add>
<add> // check the replica status after decommission is done
<add> fsckOut = runFsck(conf, 0, true, testFile, "-files", "-blocks",
<add> "-replicaDetails");
<add> assertTrue(fsckOut.contains("(DECOMMISSIONED)"));
<add> }
<add>
<add> /** Test if fsck can return -1 in case of failure.
<ide> *
<ide> * @throws Exception
<ide> */
<ide> @Test
<ide> public void testFsckError() throws Exception {
<del> MiniDFSCluster cluster = null;
<del> try {
<del> // bring up a one-node cluster
<del> Configuration conf = new HdfsConfiguration();
<del> cluster = new MiniDFSCluster.Builder(conf).build();
<del> String fileName = "/test.txt";
<del> Path filePath = new Path(fileName);
<del> FileSystem fs = cluster.getFileSystem();
<del>
<del> // create a one-block file
<del> DFSTestUtil.createFile(fs, filePath, 1L, (short)1, 1L);
<del> DFSTestUtil.waitReplication(fs, filePath, (short)1);
<del>
<del> // intentionally corrupt NN data structure
<del> INodeFile node = (INodeFile) cluster.getNamesystem().dir.getINode
<del> (fileName, true);
<del> final BlockInfo[] blocks = node.getBlocks();
<del> assertEquals(blocks.length, 1);
<del> blocks[0].setNumBytes(-1L); // set the block length to be negative
<del>
<del> // run fsck and expect a failure with -1 as the error code
<del> String outStr = runFsck(conf, -1, true, fileName);
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.FAILURE_STATUS));
<del>
<del> // clean up file system
<del> fs.delete(filePath, true);
<del> } finally {
<del> if (cluster != null) {cluster.shutdown();}
<del> }
<add> // bring up a one-node cluster
<add> cluster = new MiniDFSCluster.Builder(conf).build();
<add> String fileName = "/test.txt";
<add> Path filePath = new Path(fileName);
<add> FileSystem fs = cluster.getFileSystem();
<add>
<add> // create a one-block file
<add> DFSTestUtil.createFile(fs, filePath, 1L, (short)1, 1L);
<add> DFSTestUtil.waitReplication(fs, filePath, (short)1);
<add>
<add> // intentionally corrupt NN data structure
<add> INodeFile node = (INodeFile) cluster.getNamesystem().dir.getINode(
<add> fileName, true);
<add> final BlockInfo[] blocks = node.getBlocks();
<add> assertEquals(blocks.length, 1);
<add> blocks[0].setNumBytes(-1L); // set the block length to be negative
<add>
<add> // run fsck and expect a failure with -1 as the error code
<add> String outStr = runFsck(conf, -1, true, fileName);
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.FAILURE_STATUS));
<add>
<add> // clean up file system
<add> fs.delete(filePath, true);
<ide> }
<ide>
<del> /** check if option -list-corruptfiles of fsck command works properly */
<add> /** check if option -list-corruptfiles of fsck command works properly. */
<ide> @Test
<ide> public void testFsckListCorruptFilesBlocks() throws Exception {
<del> Configuration conf = new Configuration();
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
<ide> conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
<ide> FileSystem fs = null;
<ide>
<del> MiniDFSCluster cluster = null;
<del> try {
<del> cluster = new MiniDFSCluster.Builder(conf).build();
<del> cluster.waitActive();
<del> fs = cluster.getFileSystem();
<del> DFSTestUtil util = new DFSTestUtil.Builder().
<del> setName("testGetCorruptFiles").setNumFiles(3).setMaxLevels(1).
<del> setMaxSize(1024).build();
<del> util.createFiles(fs, "/corruptData", (short) 1);
<del> util.waitReplication(fs, "/corruptData", (short) 1);
<del>
<del> // String outStr = runFsck(conf, 0, true, "/corruptData", "-list-corruptfileblocks");
<del> String outStr = runFsck(conf, 0, false, "/corruptData", "-list-corruptfileblocks");
<del> System.out.println("1. good fsck out: " + outStr);
<del> assertTrue(outStr.contains("has 0 CORRUPT files"));
<del> // delete the blocks
<del> final String bpid = cluster.getNamesystem().getBlockPoolId();
<del> for (int i=0; i<4; i++) {
<del> for (int j=0; j<=1; j++) {
<del> File storageDir = cluster.getInstanceStorageDir(i, j);
<del> File data_dir = MiniDFSCluster.getFinalizedDir(storageDir, bpid);
<del> List<File> metadataFiles = MiniDFSCluster.getAllBlockMetadataFiles(
<del> data_dir);
<del> if (metadataFiles == null)
<del> continue;
<del> for (File metadataFile : metadataFiles) {
<del> File blockFile = Block.metaToBlockFile(metadataFile);
<del> assertTrue("Cannot remove file.", blockFile.delete());
<del> assertTrue("Cannot remove file.", metadataFile.delete());
<del> }
<add> cluster = new MiniDFSCluster.Builder(conf).build();
<add> cluster.waitActive();
<add> fs = cluster.getFileSystem();
<add> DFSTestUtil util = new DFSTestUtil.Builder().
<add> setName("testGetCorruptFiles").setNumFiles(3).setMaxLevels(1).
<add> setMaxSize(1024).build();
<add> util.createFiles(fs, "/corruptData", (short) 1);
<add> util.waitReplication(fs, "/corruptData", (short) 1);
<add>
<add> String outStr = runFsck(conf, 0, false, "/corruptData",
<add> "-list-corruptfileblocks");
<add> System.out.println("1. good fsck out: " + outStr);
<add> assertTrue(outStr.contains("has 0 CORRUPT files"));
<add> // delete the blocks
<add> final String bpid = cluster.getNamesystem().getBlockPoolId();
<add> for (int i=0; i<4; i++) {
<add> for (int j=0; j<=1; j++) {
<add> File storageDir = cluster.getInstanceStorageDir(i, j);
<add> File dataDir = MiniDFSCluster.getFinalizedDir(storageDir, bpid);
<add> List<File> metadataFiles = MiniDFSCluster.getAllBlockMetadataFiles(
<add> dataDir);
<add> if (metadataFiles == null) {
<add> continue;
<ide> }
<del> }
<del>
<del> // wait for the namenode to see the corruption
<del> final NamenodeProtocols namenode = cluster.getNameNodeRpc();
<del> CorruptFileBlocks corruptFileBlocks = namenode
<add> for (File metadataFile : metadataFiles) {
<add> File blockFile = Block.metaToBlockFile(metadataFile);
<add> assertTrue("Cannot remove file.", blockFile.delete());
<add> assertTrue("Cannot remove file.", metadataFile.delete());
<add> }
<add> }
<add> }
<add>
<add> // wait for the namenode to see the corruption
<add> final NamenodeProtocols namenode = cluster.getNameNodeRpc();
<add> CorruptFileBlocks corruptFileBlocks = namenode
<add> .listCorruptFileBlocks("/corruptData", null);
<add> int numCorrupt = corruptFileBlocks.getFiles().length;
<add> while (numCorrupt == 0) {
<add> Thread.sleep(1000);
<add> corruptFileBlocks = namenode
<ide> .listCorruptFileBlocks("/corruptData", null);
<del> int numCorrupt = corruptFileBlocks.getFiles().length;
<del> while (numCorrupt == 0) {
<del> Thread.sleep(1000);
<del> corruptFileBlocks = namenode
<del> .listCorruptFileBlocks("/corruptData", null);
<del> numCorrupt = corruptFileBlocks.getFiles().length;
<del> }
<del> outStr = runFsck(conf, -1, true, "/corruptData", "-list-corruptfileblocks");
<del> System.out.println("2. bad fsck out: " + outStr);
<del> assertTrue(outStr.contains("has 3 CORRUPT files"));
<del>
<del> // Do a listing on a dir which doesn't have any corrupt blocks and validate
<del> util.createFiles(fs, "/goodData");
<del> outStr = runFsck(conf, 0, true, "/goodData", "-list-corruptfileblocks");
<del> System.out.println("3. good fsck out: " + outStr);
<del> assertTrue(outStr.contains("has 0 CORRUPT files"));
<del> util.cleanup(fs,"/corruptData");
<del> util.cleanup(fs, "/goodData");
<del> } finally {
<del> if (cluster != null) {cluster.shutdown();}
<del> }
<add> numCorrupt = corruptFileBlocks.getFiles().length;
<add> }
<add> outStr = runFsck(conf, -1, true, "/corruptData", "-list-corruptfileblocks");
<add> System.out.println("2. bad fsck out: " + outStr);
<add> assertTrue(outStr.contains("has 3 CORRUPT files"));
<add>
<add> // Do a listing on a dir which doesn't have any corrupt blocks and validate
<add> util.createFiles(fs, "/goodData");
<add> outStr = runFsck(conf, 0, true, "/goodData", "-list-corruptfileblocks");
<add> System.out.println("3. good fsck out: " + outStr);
<add> assertTrue(outStr.contains("has 0 CORRUPT files"));
<add> util.cleanup(fs, "/corruptData");
<add> util.cleanup(fs, "/goodData");
<ide> }
<ide>
<ide> /**
<ide> */
<ide> @Test
<ide> public void testToCheckTheFsckCommandOnIllegalArguments() throws Exception {
<del> MiniDFSCluster cluster = null;
<del> try {
<del> // bring up a one-node cluster
<del> Configuration conf = new HdfsConfiguration();
<del> cluster = new MiniDFSCluster.Builder(conf).build();
<del> String fileName = "/test.txt";
<del> Path filePath = new Path(fileName);
<del> FileSystem fs = cluster.getFileSystem();
<del>
<del> // create a one-block file
<del> DFSTestUtil.createFile(fs, filePath, 1L, (short) 1, 1L);
<del> DFSTestUtil.waitReplication(fs, filePath, (short) 1);
<del>
<del> // passing illegal option
<del> String outStr = runFsck(conf, -1, true, fileName, "-thisIsNotAValidFlag");
<del> System.out.println(outStr);
<del> assertTrue(!outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del>
<del> // passing multiple paths are arguments
<del> outStr = runFsck(conf, -1, true, "/", fileName);
<del> System.out.println(outStr);
<del> assertTrue(!outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> // clean up file system
<del> fs.delete(filePath, true);
<del> } finally {
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<add> // bring up a one-node cluster
<add> cluster = new MiniDFSCluster.Builder(conf).build();
<add> String fileName = "/test.txt";
<add> Path filePath = new Path(fileName);
<add> FileSystem fs = cluster.getFileSystem();
<add>
<add> // create a one-block file
<add> DFSTestUtil.createFile(fs, filePath, 1L, (short) 1, 1L);
<add> DFSTestUtil.waitReplication(fs, filePath, (short) 1);
<add>
<add> // passing illegal option
<add> String outStr = runFsck(conf, -1, true, fileName, "-thisIsNotAValidFlag");
<add> System.out.println(outStr);
<add> assertTrue(!outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add>
<add> // passing multiple paths are arguments
<add> outStr = runFsck(conf, -1, true, "/", fileName);
<add> System.out.println(outStr);
<add> assertTrue(!outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> // clean up file system
<add> fs.delete(filePath, true);
<ide> }
<ide>
<ide> /**
<del> * Tests that the # of missing block replicas and expected replicas is correct
<add> * Tests that the # of missing block replicas and expected replicas is
<add> * correct.
<ide> * @throws IOException
<ide> */
<ide> @Test
<ide> public void testFsckMissingReplicas() throws IOException {
<ide> // Desired replication factor
<del> // Set this higher than NUM_REPLICAS so it's under-replicated
<del> final short REPL_FACTOR = 2;
<add> // Set this higher than numReplicas so it's under-replicated
<add> final short replFactor = 2;
<ide> // Number of replicas to actually start
<del> final short NUM_REPLICAS = 1;
<add> final short numReplicas = 1;
<ide> // Number of blocks to write
<del> final short NUM_BLOCKS = 3;
<add> final short numBlocks = 3;
<ide> // Set a small-ish blocksize
<ide> final long blockSize = 512;
<ide>
<del> Configuration conf = new Configuration();
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
<ide>
<del> MiniDFSCluster cluster = null;
<ide> DistributedFileSystem dfs = null;
<ide>
<del> try {
<del> // Startup a minicluster
<del> cluster =
<del> new MiniDFSCluster.Builder(conf).numDataNodes(NUM_REPLICAS).build();
<del> assertNotNull("Failed Cluster Creation", cluster);
<del> cluster.waitClusterUp();
<del> dfs = cluster.getFileSystem();
<del> assertNotNull("Failed to get FileSystem", dfs);
<del>
<del> // Create a file that will be intentionally under-replicated
<del> final String pathString = new String("/testfile");
<del> final Path path = new Path(pathString);
<del> long fileLen = blockSize * NUM_BLOCKS;
<del> DFSTestUtil.createFile(dfs, path, fileLen, REPL_FACTOR, 1);
<del>
<del> // Create an under-replicated file
<del> NameNode namenode = cluster.getNameNode();
<del> NetworkTopology nettop = cluster.getNamesystem().getBlockManager()
<del> .getDatanodeManager().getNetworkTopology();
<del> Map<String,String[]> pmap = new HashMap<String, String[]>();
<del> Writer result = new StringWriter();
<del> PrintWriter out = new PrintWriter(result, true);
<del> InetAddress remoteAddress = InetAddress.getLocalHost();
<del> NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
<del> NUM_REPLICAS, remoteAddress);
<del>
<del> // Run the fsck and check the Result
<del> final HdfsFileStatus file =
<del> namenode.getRpcServer().getFileInfo(pathString);
<del> assertNotNull(file);
<del> Result replRes = new ReplicationResult(conf);
<del> Result ecRes = new ErasureCodingResult(conf);
<del> fsck.check(pathString, file, replRes, ecRes);
<del> // Also print the output from the fsck, for ex post facto sanity checks
<del> System.out.println(result.toString());
<del> assertEquals(replRes.missingReplicas,
<del> (NUM_BLOCKS*REPL_FACTOR) - (NUM_BLOCKS*NUM_REPLICAS));
<del> assertEquals(replRes.numExpectedReplicas, NUM_BLOCKS*REPL_FACTOR);
<del> } finally {
<del> if(dfs != null) {
<del> dfs.close();
<del> }
<del> if(cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<add> // Startup a minicluster
<add> cluster =
<add> new MiniDFSCluster.Builder(conf).numDataNodes(numReplicas).build();
<add> assertNotNull("Failed Cluster Creation", cluster);
<add> cluster.waitClusterUp();
<add> dfs = cluster.getFileSystem();
<add> assertNotNull("Failed to get FileSystem", dfs);
<add>
<add> // Create a file that will be intentionally under-replicated
<add> final String pathString = new String("/testfile");
<add> final Path path = new Path(pathString);
<add> long fileLen = blockSize * numBlocks;
<add> DFSTestUtil.createFile(dfs, path, fileLen, replFactor, 1);
<add>
<add> // Create an under-replicated file
<add> NameNode namenode = cluster.getNameNode();
<add> NetworkTopology nettop = cluster.getNamesystem().getBlockManager()
<add> .getDatanodeManager().getNetworkTopology();
<add> Map<String, String[]> pmap = new HashMap<String, String[]>();
<add> Writer result = new StringWriter();
<add> PrintWriter out = new PrintWriter(result, true);
<add> InetAddress remoteAddress = InetAddress.getLocalHost();
<add> NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
<add> numReplicas, remoteAddress);
<add>
<add> // Run the fsck and check the Result
<add> final HdfsFileStatus file =
<add> namenode.getRpcServer().getFileInfo(pathString);
<add> assertNotNull(file);
<add> Result replRes = new ReplicationResult(conf);
<add> Result ecRes = new ErasureCodingResult(conf);
<add> fsck.check(pathString, file, replRes, ecRes);
<add> // Also print the output from the fsck, for ex post facto sanity checks
<add> System.out.println(result.toString());
<add> assertEquals(replRes.missingReplicas,
<add> (numBlocks*replFactor) - (numBlocks*numReplicas));
<add> assertEquals(replRes.numExpectedReplicas, numBlocks*replFactor);
<ide> }
<ide>
<ide> /**
<del> * Tests that the # of misreplaced replicas is correct
<add> * Tests that the # of misreplaced replicas is correct.
<ide> * @throws IOException
<ide> */
<ide> @Test
<ide> public void testFsckMisPlacedReplicas() throws IOException {
<ide> // Desired replication factor
<del> final short REPL_FACTOR = 2;
<add> final short replFactor = 2;
<ide> // Number of replicas to actually start
<del> short NUM_DN = 2;
<add> short numDn = 2;
<ide> // Number of blocks to write
<del> final short NUM_BLOCKS = 3;
<add> final short numBlocks = 3;
<ide> // Set a small-ish blocksize
<ide> final long blockSize = 512;
<ide>
<del> String [] racks = {"/rack1", "/rack1"};
<del> String [] hosts = {"host1", "host2"};
<add> String[] racks = {"/rack1", "/rack1"};
<add> String[] hosts = {"host1", "host2"};
<ide>
<del> Configuration conf = new Configuration();
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
<ide>
<del> MiniDFSCluster cluster = null;
<ide> DistributedFileSystem dfs = null;
<ide>
<del> try {
<del> // Startup a minicluster
<del> cluster =
<del> new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts)
<del> .racks(racks).build();
<del> assertNotNull("Failed Cluster Creation", cluster);
<del> cluster.waitClusterUp();
<del> dfs = cluster.getFileSystem();
<del> assertNotNull("Failed to get FileSystem", dfs);
<del>
<del> // Create a file that will be intentionally under-replicated
<del> final String pathString = new String("/testfile");
<del> final Path path = new Path(pathString);
<del> long fileLen = blockSize * NUM_BLOCKS;
<del> DFSTestUtil.createFile(dfs, path, fileLen, REPL_FACTOR, 1);
<del>
<del> // Create an under-replicated file
<del> NameNode namenode = cluster.getNameNode();
<del> NetworkTopology nettop = cluster.getNamesystem().getBlockManager()
<del> .getDatanodeManager().getNetworkTopology();
<del> // Add a new node on different rack, so previous blocks' replicas
<del> // are considered to be misplaced
<del> nettop.add(DFSTestUtil.getDatanodeDescriptor("/rack2", "/host3"));
<del> NUM_DN++;
<del>
<del> Map<String,String[]> pmap = new HashMap<String, String[]>();
<del> Writer result = new StringWriter();
<del> PrintWriter out = new PrintWriter(result, true);
<del> InetAddress remoteAddress = InetAddress.getLocalHost();
<del> NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
<del> NUM_DN, remoteAddress);
<del>
<del> // Run the fsck and check the Result
<del> final HdfsFileStatus file =
<del> namenode.getRpcServer().getFileInfo(pathString);
<del> assertNotNull(file);
<del> Result replRes = new ReplicationResult(conf);
<del> Result ecRes = new ErasureCodingResult(conf);
<del> fsck.check(pathString, file, replRes, ecRes);
<del> // check misReplicatedBlock number.
<del> assertEquals(replRes.numMisReplicatedBlocks, NUM_BLOCKS);
<del> } finally {
<del> if(dfs != null) {
<del> dfs.close();
<del> }
<del> if(cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<del> }
<del>
<del> /** Test fsck with FileNotFound */
<add> // Startup a minicluster
<add> cluster =
<add> new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
<add> .racks(racks).build();
<add> assertNotNull("Failed Cluster Creation", cluster);
<add> cluster.waitClusterUp();
<add> dfs = cluster.getFileSystem();
<add> assertNotNull("Failed to get FileSystem", dfs);
<add>
<add> // Create a file that will be intentionally under-replicated
<add> final String pathString = new String("/testfile");
<add> final Path path = new Path(pathString);
<add> long fileLen = blockSize * numBlocks;
<add> DFSTestUtil.createFile(dfs, path, fileLen, replFactor, 1);
<add>
<add> // Create an under-replicated file
<add> NameNode namenode = cluster.getNameNode();
<add> NetworkTopology nettop = cluster.getNamesystem().getBlockManager()
<add> .getDatanodeManager().getNetworkTopology();
<add> // Add a new node on different rack, so previous blocks' replicas
<add> // are considered to be misplaced
<add> nettop.add(DFSTestUtil.getDatanodeDescriptor("/rack2", "/host3"));
<add> numDn++;
<add>
<add> Map<String, String[]> pmap = new HashMap<String, String[]>();
<add> Writer result = new StringWriter();
<add> PrintWriter out = new PrintWriter(result, true);
<add> InetAddress remoteAddress = InetAddress.getLocalHost();
<add> NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
<add> numDn, remoteAddress);
<add>
<add> // Run the fsck and check the Result
<add> final HdfsFileStatus file =
<add> namenode.getRpcServer().getFileInfo(pathString);
<add> assertNotNull(file);
<add> Result replRes = new ReplicationResult(conf);
<add> Result ecRes = new ErasureCodingResult(conf);
<add> fsck.check(pathString, file, replRes, ecRes);
<add> // check misReplicatedBlock number.
<add> assertEquals(replRes.numMisReplicatedBlocks, numBlocks);
<add> }
<add>
<add> /** Test fsck with FileNotFound. */
<ide> @Test
<ide> public void testFsckFileNotFound() throws Exception {
<ide>
<ide> // Number of replicas to actually start
<del> final short NUM_REPLICAS = 1;
<del>
<del> Configuration conf = new Configuration();
<add> final short numReplicas = 1;
<add>
<ide> NameNode namenode = mock(NameNode.class);
<ide> NetworkTopology nettop = mock(NetworkTopology.class);
<del> Map<String,String[]> pmap = new HashMap<>();
<add> Map<String, String[]> pmap = new HashMap<>();
<ide> Writer result = new StringWriter();
<ide> PrintWriter out = new PrintWriter(result, true);
<ide> InetAddress remoteAddress = InetAddress.getLocalHost();
<ide> when(blockManager.getDatanodeManager()).thenReturn(dnManager);
<ide>
<ide> NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
<del> NUM_REPLICAS, remoteAddress);
<add> numReplicas, remoteAddress);
<ide>
<ide> String pathString = "/tmp/testFile";
<ide>
<ide> FsPermission perms = FsPermission.getDefault();
<ide> String owner = "foo";
<ide> String group = "bar";
<del> byte [] symlink = null;
<del> byte [] path = DFSUtil.string2Bytes(pathString);
<add> byte[] symlink = null;
<add> byte[] path = DFSUtil.string2Bytes(pathString);
<ide> long fileId = 312321L;
<ide> int numChildren = 1;
<ide> byte storagePolicy = 0;
<ide> assertTrue(replRes.isHealthy());
<ide> }
<ide>
<del> /** Test fsck with symlinks in the filesystem */
<add> /** Test fsck with symlinks in the filesystem. */
<ide> @Test
<ide> public void testFsckSymlink() throws Exception {
<ide> final DFSTestUtil util = new DFSTestUtil.Builder().
<ide> setName(getClass().getSimpleName()).setNumFiles(1).build();
<del> final Configuration conf = new HdfsConfiguration();
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<ide>
<del> MiniDFSCluster cluster = null;
<ide> FileSystem fs = null;
<del> try {
<del> final long precision = 1L;
<del> conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, precision);
<del> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<del> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<del> fs = cluster.getFileSystem();
<del> final String fileName = "/srcdat";
<del> util.createFiles(fs, fileName);
<del> final FileContext fc = FileContext.getFileContext(
<del> cluster.getConfiguration(0));
<del> final Path file = new Path(fileName);
<del> final Path symlink = new Path("/srcdat-symlink");
<del> fc.createSymlink(file, symlink, false);
<del> util.waitReplication(fs, fileName, (short)3);
<del> long aTime = fc.getFileStatus(symlink).getAccessTime();
<del> Thread.sleep(precision);
<del> setupAuditLogs();
<del> String outStr = runFsck(conf, 0, true, "/");
<del> verifyAuditLogs();
<del> assertEquals(aTime, fc.getFileStatus(symlink).getAccessTime());
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> assertTrue(outStr.contains("Total symlinks:\t\t1"));
<del> util.cleanup(fs, fileName);
<del> } finally {
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> if (cluster != null) { cluster.shutdown(); }
<del> }
<add> final long precision = 1L;
<add> conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY,
<add> precision);
<add> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<add> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(4).build();
<add> fs = cluster.getFileSystem();
<add> final String fileName = "/srcdat";
<add> util.createFiles(fs, fileName);
<add> final FileContext fc = FileContext.getFileContext(
<add> cluster.getConfiguration(0));
<add> final Path file = new Path(fileName);
<add> final Path symlink = new Path("/srcdat-symlink");
<add> fc.createSymlink(file, symlink, false);
<add> util.waitReplication(fs, fileName, (short)3);
<add> long aTime = fc.getFileStatus(symlink).getAccessTime();
<add> Thread.sleep(precision);
<add> setupAuditLogs();
<add> String outStr = runFsck(conf, 0, true, "/");
<add> verifyAuditLogs();
<add> assertEquals(aTime, fc.getFileStatus(symlink).getAccessTime());
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> assertTrue(outStr.contains("Total symlinks:\t\t1"));
<add> util.cleanup(fs, fileName);
<ide> }
<ide>
<ide> /**
<del> * Test for including the snapshot files in fsck report
<add> * Test for including the snapshot files in fsck report.
<ide> */
<ide> @Test
<ide> public void testFsckForSnapshotFiles() throws Exception {
<del> final Configuration conf = new HdfsConfiguration();
<del> MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1)
<add> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1)
<ide> .build();
<del> try {
<del> String runFsck = runFsck(conf, 0, true, "/", "-includeSnapshots",
<del> "-files");
<del> assertTrue(runFsck.contains("HEALTHY"));
<del> final String fileName = "/srcdat";
<del> DistributedFileSystem hdfs = cluster.getFileSystem();
<del> Path file1 = new Path(fileName);
<del> DFSTestUtil.createFile(hdfs, file1, 1024, (short) 1, 1000L);
<del> hdfs.allowSnapshot(new Path("/"));
<del> hdfs.createSnapshot(new Path("/"), "mySnapShot");
<del> runFsck = runFsck(conf, 0, true, "/", "-includeSnapshots", "-files");
<del> assertTrue(runFsck.contains("/.snapshot/mySnapShot/srcdat"));
<del> runFsck = runFsck(conf, 0, true, "/", "-files");
<del> assertFalse(runFsck.contains("mySnapShot"));
<del> } finally {
<del> cluster.shutdown();
<del> }
<add> String runFsck = runFsck(conf, 0, true, "/", "-includeSnapshots",
<add> "-files");
<add> assertTrue(runFsck.contains("HEALTHY"));
<add> final String fileName = "/srcdat";
<add> DistributedFileSystem hdfs = cluster.getFileSystem();
<add> Path file1 = new Path(fileName);
<add> DFSTestUtil.createFile(hdfs, file1, 1024, (short) 1, 1000L);
<add> hdfs.allowSnapshot(new Path("/"));
<add> hdfs.createSnapshot(new Path("/"), "mySnapShot");
<add> runFsck = runFsck(conf, 0, true, "/", "-includeSnapshots", "-files");
<add> assertTrue(runFsck.contains("/.snapshot/mySnapShot/srcdat"));
<add> runFsck = runFsck(conf, 0, true, "/", "-files");
<add> assertFalse(runFsck.contains("mySnapShot"));
<ide> }
<ide>
<ide> /**
<del> * Test for blockIdCK
<add> * Test for blockIdCK.
<ide> */
<ide>
<ide> @Test
<ide> public void testBlockIdCK() throws Exception {
<ide>
<del> final short REPL_FACTOR = 2;
<del> short NUM_DN = 2;
<add> final short replFactor = 2;
<add> short numDn = 2;
<ide> final long blockSize = 512;
<ide>
<del> String [] racks = {"/rack1", "/rack2"};
<del> String [] hosts = {"host1", "host2"};
<del>
<del> Configuration conf = new Configuration();
<add> String[] racks = {"/rack1", "/rack2"};
<add> String[] hosts = {"host1", "host2"};
<add>
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
<ide> conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 2);
<ide>
<del> MiniDFSCluster cluster = null;
<ide> DistributedFileSystem dfs = null;
<ide> cluster =
<del> new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts)
<add> new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
<ide> .racks(racks).build();
<del>
<del> assertNotNull("Failed Cluster Creation", cluster);
<del> cluster.waitClusterUp();
<del> dfs = cluster.getFileSystem();
<del> assertNotNull("Failed to get FileSystem", dfs);
<del>
<del> DFSTestUtil util = new DFSTestUtil.Builder().
<del> setName(getClass().getSimpleName()).setNumFiles(1).build();
<del> //create files
<del> final String pathString = new String("/testfile");
<del> final Path path = new Path(pathString);
<del> util.createFile(dfs, path, 1024, REPL_FACTOR , 1000L);
<del> util.waitReplication(dfs, path, REPL_FACTOR);
<del> StringBuilder sb = new StringBuilder();
<del> for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
<del> sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
<del> }
<del> String[] bIds = sb.toString().split(" ");
<del>
<del> //run fsck
<del> try {
<del> //illegal input test
<del> String runFsckResult = runFsck(conf, 0, true, "/", "-blockId",
<del> "not_a_block_id");
<del> assertTrue(runFsckResult.contains("Incorrect blockId format:"));
<del>
<del> //general test
<del> runFsckResult = runFsck(conf, 0, true, "/", "-blockId", sb.toString());
<del> assertTrue(runFsckResult.contains(bIds[0]));
<del> assertTrue(runFsckResult.contains(bIds[1]));
<del> assertTrue(runFsckResult.contains(
<del> "Block replica on datanode/rack: host1/rack1 is HEALTHY"));
<del> assertTrue(runFsckResult.contains(
<del> "Block replica on datanode/rack: host2/rack2 is HEALTHY"));
<del> } finally {
<del> cluster.shutdown();
<del> }
<del> }
<del>
<del> /**
<del> * Test for blockIdCK with datanode decommission
<del> */
<del> @Test
<del> public void testBlockIdCKDecommission() throws Exception {
<del>
<del> final short REPL_FACTOR = 1;
<del> short NUM_DN = 2;
<del> final long blockSize = 512;
<del> boolean checkDecommissionInProgress = false;
<del> String [] racks = {"/rack1", "/rack2"};
<del> String [] hosts = {"host1", "host2"};
<del>
<del> Configuration conf = new Configuration();
<del> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
<del> conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 2);
<del>
<del> MiniDFSCluster cluster;
<del> DistributedFileSystem dfs ;
<del> cluster =
<del> new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts)
<del> .racks(racks).build();
<ide>
<ide> assertNotNull("Failed Cluster Creation", cluster);
<ide> cluster.waitClusterUp();
<ide> //create files
<ide> final String pathString = new String("/testfile");
<ide> final Path path = new Path(pathString);
<del> util.createFile(dfs, path, 1024, REPL_FACTOR, 1000L);
<del> util.waitReplication(dfs, path, REPL_FACTOR);
<add> util.createFile(dfs, path, 1024, replFactor, 1000L);
<add> util.waitReplication(dfs, path, replFactor);
<ide> StringBuilder sb = new StringBuilder();
<ide> for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
<ide> sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
<ide> }
<ide> String[] bIds = sb.toString().split(" ");
<add>
<add> //run fsck
<add> //illegal input test
<add> String runFsckResult = runFsck(conf, 0, true, "/", "-blockId",
<add> "not_a_block_id");
<add> assertTrue(runFsckResult.contains("Incorrect blockId format:"));
<add>
<add> //general test
<add> runFsckResult = runFsck(conf, 0, true, "/", "-blockId", sb.toString());
<add> assertTrue(runFsckResult.contains(bIds[0]));
<add> assertTrue(runFsckResult.contains(bIds[1]));
<add> assertTrue(runFsckResult.contains(
<add> "Block replica on datanode/rack: host1/rack1 is HEALTHY"));
<add> assertTrue(runFsckResult.contains(
<add> "Block replica on datanode/rack: host2/rack2 is HEALTHY"));
<add> }
<add>
<add> /**
<add> * Test for blockIdCK with datanode decommission.
<add> */
<add> @Test
<add> public void testBlockIdCKDecommission() throws Exception {
<add>
<add> final short replFactor = 1;
<add> short numDn = 2;
<add> final long blockSize = 512;
<add> boolean checkDecommissionInProgress = false;
<add> String[] racks = {"/rack1", "/rack2"};
<add> String[] hosts = {"host1", "host2"};
<add>
<add> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
<add> conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 2);
<add>
<add> DistributedFileSystem dfs;
<add> cluster =
<add> new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
<add> .racks(racks).build();
<add>
<add> assertNotNull("Failed Cluster Creation", cluster);
<add> cluster.waitClusterUp();
<add> dfs = cluster.getFileSystem();
<add> assertNotNull("Failed to get FileSystem", dfs);
<add>
<add> DFSTestUtil util = new DFSTestUtil.Builder().
<add> setName(getClass().getSimpleName()).setNumFiles(1).build();
<add> //create files
<add> final String pathString = new String("/testfile");
<add> final Path path = new Path(pathString);
<add> util.createFile(dfs, path, 1024, replFactor, 1000L);
<add> util.waitReplication(dfs, path, replFactor);
<add> StringBuilder sb = new StringBuilder();
<add> for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
<add> sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
<add> }
<add> String[] bIds = sb.toString().split(" ");
<add>
<add> //make sure datanode that has replica is fine before decommission
<add> String outStr = runFsck(conf, 0, true, "/", "-blockId", bIds[0]);
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add>
<add> //decommission datanode
<add> FSNamesystem fsn = cluster.getNameNode().getNamesystem();
<add> BlockManager bm = fsn.getBlockManager();
<add> ExtendedBlock eb = util.getFirstBlock(dfs, path);
<add> BlockCollection bc = null;
<ide> try {
<del> //make sure datanode that has replica is fine before decommission
<del> String outStr = runFsck(conf, 0, true, "/", "-blockId", bIds[0]);
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del>
<del> //decommission datanode
<del> FSNamesystem fsn = cluster.getNameNode().getNamesystem();
<del> BlockManager bm = fsn.getBlockManager();
<del> ExtendedBlock eb = util.getFirstBlock(dfs, path);
<del> BlockCollection bc = null;
<del> try {
<del> fsn.writeLock();
<del> BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
<del> bc = fsn.getBlockCollection(bi);
<del> } finally {
<del> fsn.writeUnlock();
<del> }
<del> DatanodeDescriptor dn = bc.getBlocks()[0].getDatanode(0);
<del> bm.getDatanodeManager().getDecomManager().startDecommission(dn);
<del> String dnName = dn.getXferAddr();
<del>
<del> //wait for decommission start
<del> DatanodeInfo datanodeInfo = null;
<del> int count = 0;
<del> do {
<del> Thread.sleep(2000);
<del> for (DatanodeInfo info : dfs.getDataNodeStats()) {
<del> if (dnName.equals(info.getXferAddr())) {
<del> datanodeInfo = info;
<del> }
<add> fsn.writeLock();
<add> BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
<add> bc = fsn.getBlockCollection(bi);
<add> } finally {
<add> fsn.writeUnlock();
<add> }
<add> DatanodeDescriptor dn = bc.getBlocks()[0].getDatanode(0);
<add> bm.getDatanodeManager().getDecomManager().startDecommission(dn);
<add> String dnName = dn.getXferAddr();
<add>
<add> //wait for decommission start
<add> DatanodeInfo datanodeInfo = null;
<add> int count = 0;
<add> do {
<add> Thread.sleep(2000);
<add> for (DatanodeInfo info : dfs.getDataNodeStats()) {
<add> if (dnName.equals(info.getXferAddr())) {
<add> datanodeInfo = info;
<ide> }
<del> //check decommissioning only once
<del> if(!checkDecommissionInProgress && datanodeInfo != null
<del> && datanodeInfo.isDecommissionInProgress()) {
<del> String fsckOut = runFsck(conf, 3, true, "/", "-blockId", bIds[0]);
<del> assertTrue(fsckOut.contains(NamenodeFsck.DECOMMISSIONING_STATUS));
<del> checkDecommissionInProgress = true;
<del> }
<del> } while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
<del>
<del> //check decommissioned
<del> String fsckOut = runFsck(conf, 2, true, "/", "-blockId", bIds[0]);
<del> assertTrue(fsckOut.contains(NamenodeFsck.DECOMMISSIONED_STATUS));
<del> } finally {
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<add> }
<add> //check decommissioning only once
<add> if(!checkDecommissionInProgress && datanodeInfo != null
<add> && datanodeInfo.isDecommissionInProgress()) {
<add> String fsckOut = runFsck(conf, 3, true, "/", "-blockId", bIds[0]);
<add> assertTrue(fsckOut.contains(NamenodeFsck.DECOMMISSIONING_STATUS));
<add> checkDecommissionInProgress = true;
<add> }
<add> } while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
<add>
<add> //check decommissioned
<add> String fsckOut = runFsck(conf, 2, true, "/", "-blockId", bIds[0]);
<add> assertTrue(fsckOut.contains(NamenodeFsck.DECOMMISSIONED_STATUS));
<ide> }
<ide>
<ide> /**
<del> * Test for blockIdCK with block corruption
<add> * Test for blockIdCK with block corruption.
<ide> */
<ide> @Test
<ide> public void testBlockIdCKCorruption() throws Exception {
<del> short NUM_DN = 1;
<add> short numDn = 1;
<ide> final long blockSize = 512;
<ide> Random random = new Random();
<ide> ExtendedBlock block;
<ide> short repFactor = 1;
<del> String [] racks = {"/rack1"};
<del> String [] hosts = {"host1"};
<del>
<del> Configuration conf = new Configuration();
<add> String[] racks = {"/rack1"};
<add> String[] hosts = {"host1"};
<add>
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
<ide> // Set short retry timeouts so this test runs faster
<ide> conf.setInt(HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY, 10);
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
<ide> conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
<ide>
<del> MiniDFSCluster cluster = null;
<ide> DistributedFileSystem dfs = null;
<del> try {
<del> cluster =
<del> new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts)
<del> .racks(racks).build();
<del>
<del> assertNotNull("Failed Cluster Creation", cluster);
<del> cluster.waitClusterUp();
<del> dfs = cluster.getFileSystem();
<del> assertNotNull("Failed to get FileSystem", dfs);
<del>
<del> DFSTestUtil util = new DFSTestUtil.Builder().
<add> cluster =
<add> new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
<add> .racks(racks).build();
<add>
<add> assertNotNull("Failed Cluster Creation", cluster);
<add> cluster.waitClusterUp();
<add> dfs = cluster.getFileSystem();
<add> assertNotNull("Failed to get FileSystem", dfs);
<add>
<add> DFSTestUtil util = new DFSTestUtil.Builder().
<ide> setName(getClass().getSimpleName()).setNumFiles(1).build();
<del> //create files
<del> final String pathString = new String("/testfile");
<del> final Path path = new Path(pathString);
<del> util.createFile(dfs, path, 1024, repFactor, 1000L);
<del> util.waitReplication(dfs, path, repFactor);
<del> StringBuilder sb = new StringBuilder();
<del> for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
<del> sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
<del> }
<del> String[] bIds = sb.toString().split(" ");
<del>
<del> //make sure block is healthy before we corrupt it
<del> String outStr = runFsck(conf, 0, true, "/", "-blockId", bIds[0]);
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del>
<del> // corrupt replicas
<del> block = DFSTestUtil.getFirstBlock(dfs, path);
<del> File blockFile = cluster.getBlockFile(0, block);
<del> if (blockFile != null && blockFile.exists()) {
<del> RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
<del> FileChannel channel = raFile.getChannel();
<del> String badString = "BADBAD";
<del> int rand = random.nextInt((int) channel.size()/2);
<del> raFile.seek(rand);
<del> raFile.write(badString.getBytes());
<del> raFile.close();
<del> }
<del>
<del> util.waitCorruptReplicas(dfs, cluster.getNamesystem(), path, block, 1);
<del>
<del> outStr = runFsck(conf, 1, false, "/", "-blockId", block.getBlockName());
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<del> } finally {
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<add> //create files
<add> final String pathString = new String("/testfile");
<add> final Path path = new Path(pathString);
<add> util.createFile(dfs, path, 1024, repFactor, 1000L);
<add> util.waitReplication(dfs, path, repFactor);
<add> StringBuilder sb = new StringBuilder();
<add> for (LocatedBlock lb: util.getAllBlocks(dfs, path)){
<add> sb.append(lb.getBlock().getLocalBlock().getBlockName()+" ");
<add> }
<add> String[] bIds = sb.toString().split(" ");
<add>
<add> //make sure block is healthy before we corrupt it
<add> String outStr = runFsck(conf, 0, true, "/", "-blockId", bIds[0]);
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add>
<add> // corrupt replicas
<add> block = DFSTestUtil.getFirstBlock(dfs, path);
<add> File blockFile = cluster.getBlockFile(0, block);
<add> if (blockFile != null && blockFile.exists()) {
<add> RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
<add> FileChannel channel = raFile.getChannel();
<add> String badString = "BADBAD";
<add> int rand = random.nextInt((int) channel.size()/2);
<add> raFile.seek(rand);
<add> raFile.write(badString.getBytes());
<add> raFile.close();
<add> }
<add>
<add> util.waitCorruptReplicas(dfs, cluster.getNamesystem(), path, block, 1);
<add>
<add> outStr = runFsck(conf, 1, false, "/", "-blockId", block.getBlockName());
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<ide> }
<ide>
<ide> private void writeFile(final DistributedFileSystem dfs,
<ide> }
<ide>
<ide> private void writeFile(final DistributedFileSystem dfs,
<del> String dirName, String fileName, String StoragePolicy) throws IOException {
<add> String dirName, String fileName, String storagePolicy)
<add> throws IOException {
<ide> Path dirPath = new Path(dirName);
<ide> dfs.mkdirs(dirPath);
<del> dfs.setStoragePolicy(dirPath, StoragePolicy);
<add> dfs.setStoragePolicy(dirPath, storagePolicy);
<ide> writeFile(dfs, dirPath, fileName);
<ide> }
<ide>
<ide> /**
<del> * Test storage policy display
<add> * Test storage policy display.
<ide> */
<ide> @Test
<ide> public void testStoragePoliciesCK() throws Exception {
<del> final Configuration conf = new HdfsConfiguration();
<del> final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
<add> cluster = new MiniDFSCluster.Builder(conf)
<ide> .numDataNodes(3)
<ide> .storageTypes(
<ide> new StorageType[] {StorageType.DISK, StorageType.ARCHIVE})
<ide> .build();
<del> try {
<del> cluster.waitActive();
<del> final DistributedFileSystem dfs = cluster.getFileSystem();
<del> writeFile(dfs, "/testhot", "file", "HOT");
<del> writeFile(dfs, "/testwarm", "file", "WARM");
<del> writeFile(dfs, "/testcold", "file", "COLD");
<del> String outStr = runFsck(conf, 0, true, "/", "-storagepolicies");
<del> assertTrue(outStr.contains("DISK:3(HOT)"));
<del> assertTrue(outStr.contains("DISK:1,ARCHIVE:2(WARM)"));
<del> assertTrue(outStr.contains("ARCHIVE:3(COLD)"));
<del> assertTrue(outStr.contains("All blocks satisfy specified storage policy."));
<del> dfs.setStoragePolicy(new Path("/testhot"), "COLD");
<del> dfs.setStoragePolicy(new Path("/testwarm"), "COLD");
<del> outStr = runFsck(conf, 0, true, "/", "-storagepolicies");
<del> assertTrue(outStr.contains("DISK:3(HOT)"));
<del> assertTrue(outStr.contains("DISK:1,ARCHIVE:2(WARM)"));
<del> assertTrue(outStr.contains("ARCHIVE:3(COLD)"));
<del> assertFalse(outStr.contains("All blocks satisfy specified storage policy."));
<del> } finally {
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<add> cluster.waitActive();
<add> final DistributedFileSystem dfs = cluster.getFileSystem();
<add> writeFile(dfs, "/testhot", "file", "HOT");
<add> writeFile(dfs, "/testwarm", "file", "WARM");
<add> writeFile(dfs, "/testcold", "file", "COLD");
<add> String outStr = runFsck(conf, 0, true, "/", "-storagepolicies");
<add> assertTrue(outStr.contains("DISK:3(HOT)"));
<add> assertTrue(outStr.contains("DISK:1,ARCHIVE:2(WARM)"));
<add> assertTrue(outStr.contains("ARCHIVE:3(COLD)"));
<add> assertTrue(outStr.contains("All blocks satisfy specified storage policy."));
<add> dfs.setStoragePolicy(new Path("/testhot"), "COLD");
<add> dfs.setStoragePolicy(new Path("/testwarm"), "COLD");
<add> outStr = runFsck(conf, 0, true, "/", "-storagepolicies");
<add> assertTrue(outStr.contains("DISK:3(HOT)"));
<add> assertTrue(outStr.contains("DISK:1,ARCHIVE:2(WARM)"));
<add> assertTrue(outStr.contains("ARCHIVE:3(COLD)"));
<add> assertFalse(outStr.contains(
<add> "All blocks satisfy specified storage policy."));
<ide> }
<ide>
<ide> /**
<del> * Test for blocks on decommissioning hosts are not shown as missing
<add> * Test for blocks on decommissioning hosts are not shown as missing.
<ide> */
<ide> @Test
<ide> public void testFsckWithDecommissionedReplicas() throws Exception {
<ide>
<del> final short REPL_FACTOR = 1;
<del> short NUM_DN = 2;
<add> final short replFactor = 1;
<add> short numDn = 2;
<ide> final long blockSize = 512;
<ide> final long fileSize = 1024;
<ide> boolean checkDecommissionInProgress = false;
<del> String [] racks = {"/rack1", "/rack2"};
<del> String [] hosts = {"host1", "host2"};
<del>
<del> Configuration conf = new Configuration();
<add> String[] racks = {"/rack1", "/rack2"};
<add> String[] hosts = {"host1", "host2"};
<add>
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
<ide> conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
<ide>
<del> MiniDFSCluster cluster;
<del> DistributedFileSystem dfs ;
<add> DistributedFileSystem dfs;
<ide> cluster =
<del> new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts)
<add> new MiniDFSCluster.Builder(conf).numDataNodes(numDn).hosts(hosts)
<ide> .racks(racks).build();
<ide>
<ide> assertNotNull("Failed Cluster Creation", cluster);
<ide> //create files
<ide> final String testFile = new String("/testfile");
<ide> final Path path = new Path(testFile);
<del> util.createFile(dfs, path, fileSize, REPL_FACTOR, 1000L);
<del> util.waitReplication(dfs, path, REPL_FACTOR);
<add> util.createFile(dfs, path, fileSize, replFactor, 1000L);
<add> util.waitReplication(dfs, path, replFactor);
<add>
<add> // make sure datanode that has replica is fine before decommission
<add> String outStr = runFsck(conf, 0, true, testFile);
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add>
<add> // decommission datanode
<add> FSNamesystem fsn = cluster.getNameNode().getNamesystem();
<add> BlockManager bm = fsn.getBlockManager();
<add> ExtendedBlock eb = util.getFirstBlock(dfs, path);
<add> BlockCollection bc = null;
<ide> try {
<del> // make sure datanode that has replica is fine before decommission
<del> String outStr = runFsck(conf, 0, true, testFile);
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del>
<del> // decommission datanode
<del> FSNamesystem fsn = cluster.getNameNode().getNamesystem();
<del> BlockManager bm = fsn.getBlockManager();
<del> ExtendedBlock eb = util.getFirstBlock(dfs, path);
<del> BlockCollection bc = null;
<del> try {
<del> fsn.writeLock();
<del> BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
<del> bc = fsn.getBlockCollection(bi);
<del> } finally {
<del> fsn.writeUnlock();
<del> }
<del> DatanodeDescriptor dn = bc.getBlocks()[0]
<del> .getDatanode(0);
<del> bm.getDatanodeManager().getDecomManager().startDecommission(dn);
<del> String dnName = dn.getXferAddr();
<del>
<del> // wait for decommission start
<del> DatanodeInfo datanodeInfo = null;
<del> int count = 0;
<del> do {
<del> Thread.sleep(2000);
<del> for (DatanodeInfo info : dfs.getDataNodeStats()) {
<del> if (dnName.equals(info.getXferAddr())) {
<del> datanodeInfo = info;
<del> }
<add> fsn.writeLock();
<add> BlockInfo bi = bm.getStoredBlock(eb.getLocalBlock());
<add> bc = fsn.getBlockCollection(bi);
<add> } finally {
<add> fsn.writeUnlock();
<add> }
<add> DatanodeDescriptor dn = bc.getBlocks()[0]
<add> .getDatanode(0);
<add> bm.getDatanodeManager().getDecomManager().startDecommission(dn);
<add> String dnName = dn.getXferAddr();
<add>
<add> // wait for decommission start
<add> DatanodeInfo datanodeInfo = null;
<add> int count = 0;
<add> do {
<add> Thread.sleep(2000);
<add> for (DatanodeInfo info : dfs.getDataNodeStats()) {
<add> if (dnName.equals(info.getXferAddr())) {
<add> datanodeInfo = info;
<ide> }
<del> // check the replica status should be healthy(0)
<del> // instead of corruption (1) during decommissioning
<del> if(!checkDecommissionInProgress && datanodeInfo != null
<del> && datanodeInfo.isDecommissionInProgress()) {
<del> String fsckOut = runFsck(conf, 0, true, testFile);
<del> checkDecommissionInProgress = true;
<del> }
<del> } while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
<del>
<del> // check the replica status should be healthy(0) after decommission
<del> // is done
<del> String fsckOut = runFsck(conf, 0, true, testFile);
<del> } finally {
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<add> }
<add> // check the replica status should be healthy(0)
<add> // instead of corruption (1) during decommissioning
<add> if(!checkDecommissionInProgress && datanodeInfo != null
<add> && datanodeInfo.isDecommissionInProgress()) {
<add> String fsckOut = runFsck(conf, 0, true, testFile);
<add> checkDecommissionInProgress = true;
<add> }
<add> } while (datanodeInfo != null && !datanodeInfo.isDecommissioned());
<add>
<add> // check the replica status should be healthy(0) after decommission
<add> // is done
<add> String fsckOut = runFsck(conf, 0, true, testFile);
<ide> }
<ide>
<ide> @Test
<ide> public void testECFsck() throws Exception {
<del> MiniDFSCluster cluster = null;
<ide> FileSystem fs = null;
<del> try {
<del> Configuration conf = new HdfsConfiguration();
<del> final long precision = 1L;
<del> conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, precision);
<del> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<del> int totalSize = ErasureCodingPolicyManager.getSystemDefaultPolicy().getNumDataUnits()
<del> + ErasureCodingPolicyManager.getSystemDefaultPolicy().getNumParityUnits();
<del> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(totalSize).build();
<del> fs = cluster.getFileSystem();
<del>
<del> // create a contiguous file
<del> Path replDirPath = new Path("/replicated");
<del> Path replFilePath = new Path(replDirPath, "replfile");
<del> final short factor = 3;
<del> DFSTestUtil.createFile(fs, replFilePath, 1024, factor, 0);
<del> DFSTestUtil.waitReplication(fs, replFilePath, factor);
<del>
<del> // create a large striped file
<del> Path ecDirPath = new Path("/striped");
<del> Path largeFilePath = new Path(ecDirPath, "largeFile");
<del> DFSTestUtil.createStripedFile(cluster, largeFilePath, ecDirPath, 1, 2, true);
<del>
<del> // create a small striped file
<del> Path smallFilePath = new Path(ecDirPath, "smallFile");
<del> DFSTestUtil.writeFile(fs, smallFilePath, "hello world!");
<del>
<del> long replTime = fs.getFileStatus(replFilePath).getAccessTime();
<del> long ecTime = fs.getFileStatus(largeFilePath).getAccessTime();
<del> Thread.sleep(precision);
<del> setupAuditLogs();
<del> String outStr = runFsck(conf, 0, true, "/");
<del> verifyAuditLogs();
<del> assertEquals(replTime, fs.getFileStatus(replFilePath).getAccessTime());
<del> assertEquals(ecTime, fs.getFileStatus(largeFilePath).getAccessTime());
<del> System.out.println(outStr);
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> cluster.shutdown();
<del>
<del> // restart the cluster; bring up namenode but not the data nodes
<del> cluster = new MiniDFSCluster.Builder(conf)
<del> .numDataNodes(0).format(false).build();
<del> outStr = runFsck(conf, 1, true, "/");
<del> // expect the result is corrupt
<del> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<del> System.out.println(outStr);
<del> } finally {
<del> if (fs != null) {try{fs.close();} catch(Exception e){}}
<del> if (cluster != null) { cluster.shutdown(); }
<del> }
<add> final long precision = 1L;
<add> conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY,
<add> precision);
<add> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
<add> int dataBlocks = ErasureCodingPolicyManager
<add> .getSystemDefaultPolicy().getNumDataUnits();
<add> int parityBlocks = ErasureCodingPolicyManager
<add> .getSystemDefaultPolicy().getNumParityUnits();
<add> int totalSize = dataBlocks + parityBlocks;
<add> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(totalSize).build();
<add> fs = cluster.getFileSystem();
<add>
<add> // create a contiguous file
<add> Path replDirPath = new Path("/replicated");
<add> Path replFilePath = new Path(replDirPath, "replfile");
<add> final short factor = 3;
<add> DFSTestUtil.createFile(fs, replFilePath, 1024, factor, 0);
<add> DFSTestUtil.waitReplication(fs, replFilePath, factor);
<add>
<add> // create a large striped file
<add> Path ecDirPath = new Path("/striped");
<add> Path largeFilePath = new Path(ecDirPath, "largeFile");
<add> DFSTestUtil.createStripedFile(cluster, largeFilePath, ecDirPath, 1, 2,
<add> true);
<add>
<add> // create a small striped file
<add> Path smallFilePath = new Path(ecDirPath, "smallFile");
<add> DFSTestUtil.writeFile(fs, smallFilePath, "hello world!");
<add>
<add> long replTime = fs.getFileStatus(replFilePath).getAccessTime();
<add> long ecTime = fs.getFileStatus(largeFilePath).getAccessTime();
<add> Thread.sleep(precision);
<add> setupAuditLogs();
<add> String outStr = runFsck(conf, 0, true, "/");
<add> verifyAuditLogs();
<add> assertEquals(replTime, fs.getFileStatus(replFilePath).getAccessTime());
<add> assertEquals(ecTime, fs.getFileStatus(largeFilePath).getAccessTime());
<add> System.out.println(outStr);
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add> shutdownCluster();
<add>
<add> // restart the cluster; bring up namenode but not the data nodes
<add> cluster = new MiniDFSCluster.Builder(conf)
<add> .numDataNodes(0).format(false).build();
<add> outStr = runFsck(conf, 1, true, "/");
<add> // expect the result is corrupt
<add> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<add> System.out.println(outStr);
<ide> }
<ide>
<ide> /**
<ide> */
<ide> @Test
<ide> public void testFsckListCorruptSnapshotFiles() throws Exception {
<del> Configuration conf = new Configuration();
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000);
<ide> conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
<ide> DistributedFileSystem hdfs = null;
<del> final short REPL_FACTOR = 1;
<del>
<del> MiniDFSCluster cluster = null;
<del> try {
<del> int numFiles = 3;
<del> int numSnapshots = 0;
<del> cluster = new MiniDFSCluster.Builder(conf).build();
<del> cluster.waitActive();
<del> hdfs = cluster.getFileSystem();
<del> DFSTestUtil util = new DFSTestUtil.Builder().
<del> setName("testGetCorruptFiles").setNumFiles(numFiles).setMaxLevels(1).
<del> setMaxSize(1024).build();
<del>
<del> util.createFiles(hdfs, "/corruptData", (short) 1);
<del> final Path fp = new Path("/corruptData/file");
<del> util.createFile(hdfs, fp, 1024, REPL_FACTOR, 1000L);
<del> numFiles++;
<del> util.waitReplication(hdfs, "/corruptData", (short) 1);
<del>
<del> hdfs.allowSnapshot(new Path("/corruptData"));
<del> hdfs.createSnapshot(new Path("/corruptData"), "mySnapShot");
<del> numSnapshots = numFiles;
<del>
<del> String outStr =
<del> runFsck(conf, 0, false, "/corruptData", "-list-corruptfileblocks");
<del> System.out.println("1. good fsck out: " + outStr);
<del> assertTrue(outStr.contains("has 0 CORRUPT files"));
<del> // delete the blocks
<del> final String bpid = cluster.getNamesystem().getBlockPoolId();
<del> for (int i=0; i<numFiles; i++) {
<del> for (int j=0; j<=1; j++) {
<del> File storageDir = cluster.getInstanceStorageDir(i, j);
<del> File data_dir = MiniDFSCluster.getFinalizedDir(storageDir, bpid);
<del> List<File> metadataFiles = MiniDFSCluster.getAllBlockMetadataFiles(
<del> data_dir);
<del> if (metadataFiles == null)
<del> continue;
<del> for (File metadataFile : metadataFiles) {
<del> File blockFile = Block.metaToBlockFile(metadataFile);
<del> assertTrue("Cannot remove file.", blockFile.delete());
<del> assertTrue("Cannot remove file.", metadataFile.delete());
<del> }
<add> final short replFactor = 1;
<add>
<add> int numFiles = 3;
<add> int numSnapshots = 0;
<add> cluster = new MiniDFSCluster.Builder(conf).build();
<add> cluster.waitActive();
<add> hdfs = cluster.getFileSystem();
<add> DFSTestUtil util = new DFSTestUtil.Builder().
<add> setName("testGetCorruptFiles").setNumFiles(numFiles).setMaxLevels(1).
<add> setMaxSize(1024).build();
<add>
<add> util.createFiles(hdfs, "/corruptData", (short) 1);
<add> final Path fp = new Path("/corruptData/file");
<add> util.createFile(hdfs, fp, 1024, replFactor, 1000L);
<add> numFiles++;
<add> util.waitReplication(hdfs, "/corruptData", (short) 1);
<add>
<add> hdfs.allowSnapshot(new Path("/corruptData"));
<add> hdfs.createSnapshot(new Path("/corruptData"), "mySnapShot");
<add> numSnapshots = numFiles;
<add>
<add> String outStr =
<add> runFsck(conf, 0, false, "/corruptData", "-list-corruptfileblocks");
<add> System.out.println("1. good fsck out: " + outStr);
<add> assertTrue(outStr.contains("has 0 CORRUPT files"));
<add> // delete the blocks
<add> final String bpid = cluster.getNamesystem().getBlockPoolId();
<add> for (int i=0; i<numFiles; i++) {
<add> for (int j=0; j<=1; j++) {
<add> File storageDir = cluster.getInstanceStorageDir(i, j);
<add> File dataDir = MiniDFSCluster.getFinalizedDir(storageDir, bpid);
<add> List<File> metadataFiles = MiniDFSCluster.getAllBlockMetadataFiles(
<add> dataDir);
<add> if (metadataFiles == null) {
<add> continue;
<ide> }
<del> }
<del> // Delete file when it has a snapshot
<del> hdfs.delete(fp, false);
<del> numFiles--;
<del>
<del> // wait for the namenode to see the corruption
<del> final NamenodeProtocols namenode = cluster.getNameNodeRpc();
<del> CorruptFileBlocks corruptFileBlocks = namenode
<add> for (File metadataFile : metadataFiles) {
<add> File blockFile = Block.metaToBlockFile(metadataFile);
<add> assertTrue("Cannot remove file.", blockFile.delete());
<add> assertTrue("Cannot remove file.", metadataFile.delete());
<add> }
<add> }
<add> }
<add> // Delete file when it has a snapshot
<add> hdfs.delete(fp, false);
<add> numFiles--;
<add>
<add> // wait for the namenode to see the corruption
<add> final NamenodeProtocols namenode = cluster.getNameNodeRpc();
<add> CorruptFileBlocks corruptFileBlocks = namenode
<add> .listCorruptFileBlocks("/corruptData", null);
<add> int numCorrupt = corruptFileBlocks.getFiles().length;
<add> while (numCorrupt == 0) {
<add> Thread.sleep(1000);
<add> corruptFileBlocks = namenode
<ide> .listCorruptFileBlocks("/corruptData", null);
<del> int numCorrupt = corruptFileBlocks.getFiles().length;
<del> while (numCorrupt == 0) {
<del> Thread.sleep(1000);
<del> corruptFileBlocks = namenode
<del> .listCorruptFileBlocks("/corruptData", null);
<del> numCorrupt = corruptFileBlocks.getFiles().length;
<del> }
<del>
<del> // with -includeSnapshots all files are reported
<del> outStr = runFsck(conf, -1, true, "/corruptData",
<del> "-list-corruptfileblocks", "-includeSnapshots");
<del> System.out.println("2. bad fsck include snapshot out: " + outStr);
<del> assertTrue(outStr
<del> .contains("has " + (numFiles + numSnapshots) + " CORRUPT files"));
<del> assertTrue(outStr.contains("/.snapshot/"));
<del>
<del> // without -includeSnapshots only non-snapshots are reported
<del> outStr =
<del> runFsck(conf, -1, true, "/corruptData", "-list-corruptfileblocks");
<del> System.out.println("3. bad fsck exclude snapshot out: " + outStr);
<del> assertTrue(outStr.contains("has " + numFiles + " CORRUPT files"));
<del> assertFalse(outStr.contains("/.snapshot/"));
<del> } finally {
<del> if (cluster != null) {cluster.shutdown();}
<del> }
<add> numCorrupt = corruptFileBlocks.getFiles().length;
<add> }
<add>
<add> // with -includeSnapshots all files are reported
<add> outStr = runFsck(conf, -1, true, "/corruptData",
<add> "-list-corruptfileblocks", "-includeSnapshots");
<add> System.out.println("2. bad fsck include snapshot out: " + outStr);
<add> assertTrue(outStr
<add> .contains("has " + (numFiles + numSnapshots) + " CORRUPT files"));
<add> assertTrue(outStr.contains("/.snapshot/"));
<add>
<add> // without -includeSnapshots only non-snapshots are reported
<add> outStr =
<add> runFsck(conf, -1, true, "/corruptData", "-list-corruptfileblocks");
<add> System.out.println("3. bad fsck exclude snapshot out: " + outStr);
<add> assertTrue(outStr.contains("has " + numFiles + " CORRUPT files"));
<add> assertFalse(outStr.contains("/.snapshot/"));
<ide> }
<ide>
<ide> @Test (timeout = 300000)
<ide> public void testFsckMoveAfterCorruption() throws Exception {
<del> final int DFS_BLOCK_SIZE = 512 * 1024;
<del> final int NUM_DATANODES = 1;
<del> final int REPLICATION = 1;
<del> MiniDFSCluster cluster = null;
<del> try {
<del> final Configuration conf = new HdfsConfiguration();
<del> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DFS_BLOCK_SIZE);
<del> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000L);
<del> conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
<del> conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, REPLICATION);
<del> cluster = new MiniDFSCluster.Builder(conf).build();
<del> DistributedFileSystem dfs = cluster.getFileSystem();
<del> cluster.waitActive();
<del>
<del> final String srcDir = "/srcdat";
<del> final DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck")
<del> .setMinSize(DFS_BLOCK_SIZE * 2).setMaxSize(DFS_BLOCK_SIZE * 3)
<del> .setNumFiles(1).build();
<del> util.createFiles(dfs, srcDir, (short) REPLICATION);
<del> final String fileNames[] = util.getFileNames(srcDir);
<del> FSImage.LOG.info("Created files: " + Arrays.toString(fileNames));
<del>
<del> // Run fsck here. The output is automatically logged for easier debugging
<del> String outStr = runFsck(conf, 0, true, "/", "-files", "-blocks");
<del> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<del>
<del> // Corrupt the first block
<del> final DFSClient dfsClient = new DFSClient(
<del> new InetSocketAddress("localhost", cluster.getNameNodePort()), conf);
<del> final String blockFileToCorrupt = fileNames[0];
<del> final CorruptedTestFile ctf = new CorruptedTestFile(blockFileToCorrupt,
<del> Sets.newHashSet(0), dfsClient, NUM_DATANODES, DFS_BLOCK_SIZE);
<del> ctf.corruptBlocks(cluster);
<del>
<del> // Wait for fsck to discover all the missing blocks
<del> GenericTestUtils.waitFor(new Supplier<Boolean>() {
<del> @Override
<del> public Boolean get() {
<del> try {
<del> final String str = runFsck(conf, 1, false, "/");
<del> String numCorrupt = null;
<del> for (String line : str.split(LINE_SEPARATOR)) {
<del> Matcher m = numCorruptBlocksPattern.matcher(line);
<del> if (m.matches()) {
<del> numCorrupt = m.group(1);
<del> break;
<del> }
<add> final int dfsBlockSize = 512 * 1024;
<add> final int numDatanodes = 1;
<add> final int replication = 1;
<add> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, dfsBlockSize);
<add> conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 1000L);
<add> conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1);
<add> conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, replication);
<add> cluster = new MiniDFSCluster.Builder(conf).build();
<add> DistributedFileSystem dfs = cluster.getFileSystem();
<add> cluster.waitActive();
<add>
<add> final String srcDir = "/srcdat";
<add> final DFSTestUtil util = new DFSTestUtil.Builder().setName("TestFsck")
<add> .setMinSize(dfsBlockSize * 2).setMaxSize(dfsBlockSize * 3)
<add> .setNumFiles(1).build();
<add> util.createFiles(dfs, srcDir, (short) replication);
<add> final String[] fileNames = util.getFileNames(srcDir);
<add> LOG.info("Created files: " + Arrays.toString(fileNames));
<add>
<add> // Run fsck here. The output is automatically logged for easier debugging
<add> String outStr = runFsck(conf, 0, true, "/", "-files", "-blocks");
<add> assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
<add>
<add> // Corrupt the first block
<add> final DFSClient dfsClient = new DFSClient(
<add> new InetSocketAddress("localhost", cluster.getNameNodePort()), conf);
<add> final String blockFileToCorrupt = fileNames[0];
<add> final CorruptedTestFile ctf = new CorruptedTestFile(blockFileToCorrupt,
<add> Sets.newHashSet(0), dfsClient, numDatanodes, dfsBlockSize);
<add> ctf.corruptBlocks(cluster);
<add>
<add> // Wait for fsck to discover all the missing blocks
<add> GenericTestUtils.waitFor(new Supplier<Boolean>() {
<add> @Override
<add> public Boolean get() {
<add> try {
<add> final String str = runFsck(conf, 1, false, "/");
<add> String numCorrupt = null;
<add> for (String line : str.split(LINE_SEPARATOR)) {
<add> Matcher m = NUM_CORRUPT_BLOCKS_PATTERN.matcher(line);
<add> if (m.matches()) {
<add> numCorrupt = m.group(1);
<add> break;
<ide> }
<del> if (numCorrupt == null) {
<del> Assert.fail("Cannot find corrupt blocks count in fsck output.");
<del> }
<del> if (Integer.parseInt(numCorrupt) == ctf.getTotalMissingBlocks()) {
<del> assertTrue(str.contains(NamenodeFsck.CORRUPT_STATUS));
<del> return true;
<del> }
<del> } catch (Exception e) {
<del> FSImage.LOG.error("Exception caught", e);
<del> Assert.fail("Caught unexpected exception.");
<ide> }
<del> return false;
<add> if (numCorrupt == null) {
<add> Assert.fail("Cannot find corrupt blocks count in fsck output.");
<add> }
<add> if (Integer.parseInt(numCorrupt) == ctf.getTotalMissingBlocks()) {
<add> assertTrue(str.contains(NamenodeFsck.CORRUPT_STATUS));
<add> return true;
<add> }
<add> } catch (Exception e) {
<add> LOG.error("Exception caught", e);
<add> Assert.fail("Caught unexpected exception.");
<ide> }
<del> }, 1000, 60000);
<del>
<del> runFsck(conf, 1, true, "/", "-files", "-blocks", "-racks");
<del> FSImage.LOG.info("Moving blocks to lost+found");
<del> // Fsck will return error since we corrupted a block
<del> runFsck(conf, 1, false, "/", "-move");
<del>
<del> final List<LocatedFileStatus> retVal = new ArrayList<>();
<del> final RemoteIterator<LocatedFileStatus> iter =
<del> dfs.listFiles(new Path("/lost+found"), true);
<del> while (iter.hasNext()) {
<del> retVal.add(iter.next());
<del> }
<del> FSImage.LOG.info("Items in lost+found: " + retVal);
<del>
<del> // Expect all good blocks moved, only corrupted block skipped.
<del> long totalLength = 0;
<del> for (LocatedFileStatus lfs: retVal) {
<del> totalLength += lfs.getLen();
<del> }
<del> Assert.assertTrue("Nothing is moved to lost+found!", totalLength > 0);
<del> util.cleanup(dfs, srcDir);
<del> } finally {
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<add> return false;
<add> }
<add> }, 1000, 60000);
<add>
<add> runFsck(conf, 1, true, "/", "-files", "-blocks", "-racks");
<add> LOG.info("Moving blocks to lost+found");
<add> // Fsck will return error since we corrupted a block
<add> runFsck(conf, 1, false, "/", "-move");
<add>
<add> final List<LocatedFileStatus> retVal = new ArrayList<>();
<add> final RemoteIterator<LocatedFileStatus> iter =
<add> dfs.listFiles(new Path("/lost+found"), true);
<add> while (iter.hasNext()) {
<add> retVal.add(iter.next());
<add> }
<add> LOG.info("Items in lost+found: " + retVal);
<add>
<add> // Expect all good blocks moved, only corrupted block skipped.
<add> long totalLength = 0;
<add> for (LocatedFileStatus lfs: retVal) {
<add> totalLength += lfs.getLen();
<add> }
<add> Assert.assertTrue("Nothing is moved to lost+found!", totalLength > 0);
<add> util.cleanup(dfs, srcDir);
<ide> }
<ide>
<ide> @Test(timeout = 60000)
<ide> final String[] racks = {"/rack1"};
<ide> final String[] hosts = {"127.0.0.1"};
<ide> HostsFileWriter hostsFileWriter = new HostsFileWriter();
<del> Configuration conf = new Configuration();
<ide> conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
<ide> conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, replFactor);
<ide> if (defineUpgradeDomain) {
<ide> hostsFileWriter.initialize(conf, "temp/fsckupgradedomain");
<ide> }
<ide>
<del> MiniDFSCluster cluster;
<ide> DistributedFileSystem dfs;
<ide> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDN).
<ide> hosts(hosts).racks(racks).build();
<ide> if (defineUpgradeDomain) {
<ide> hostsFileWriter.cleanup();
<ide> }
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<ide> }
<ide> }
<ide>
<ide> @Test (timeout = 300000)
<ide> public void testFsckCorruptECFile() throws Exception {
<del> MiniDFSCluster cluster = null;
<ide> DistributedFileSystem fs = null;
<add> int dataBlocks = ErasureCodingPolicyManager
<add> .getSystemDefaultPolicy().getNumDataUnits();
<add> int parityBlocks = ErasureCodingPolicyManager
<add> .getSystemDefaultPolicy().getNumParityUnits();
<add> int cellSize = ErasureCodingPolicyManager
<add> .getSystemDefaultPolicy().getCellSize();
<add> int totalSize = dataBlocks + parityBlocks;
<add> cluster = new MiniDFSCluster.Builder(conf)
<add> .numDataNodes(totalSize).build();
<add> fs = cluster.getFileSystem();
<add> Map<Integer, Integer> dnIndices = new HashMap<>();
<add> ArrayList<DataNode> dnList = cluster.getDataNodes();
<add> for (int i = 0; i < totalSize; i++) {
<add> dnIndices.put(dnList.get(i).getIpcPort(), i);
<add> }
<add>
<add> // create file
<add> Path ecDirPath = new Path("/striped");
<add> fs.mkdir(ecDirPath, FsPermission.getDirDefault());
<add> fs.getClient().setErasureCodingPolicy(ecDirPath.toString(), null);
<add> Path file = new Path(ecDirPath, "corrupted");
<add> final int length = cellSize * dataBlocks;
<add> final byte[] bytes = StripedFileTestUtil.generateBytes(length);
<add> DFSTestUtil.writeFile(fs, file, bytes);
<add>
<add> LocatedStripedBlock lsb = (LocatedStripedBlock)fs.getClient()
<add> .getLocatedBlocks(file.toString(), 0, cellSize * dataBlocks).get(0);
<add> final LocatedBlock[] blks = StripedBlockUtil.parseStripedBlockGroup(lsb,
<add> cellSize, dataBlocks, parityBlocks);
<add>
<add> // make an unrecoverable ec file with corrupted blocks
<add> for(int i = 0; i < parityBlocks + 1; i++) {
<add> int ipcPort = blks[i].getLocations()[0].getIpcPort();
<add> int dnIndex = dnIndices.get(ipcPort);
<add> File storageDir = cluster.getInstanceStorageDir(dnIndex, 0);
<add> File blkFile = MiniDFSCluster.getBlockFile(storageDir,
<add> blks[i].getBlock());
<add> Assert.assertTrue("Block file does not exist", blkFile.exists());
<add>
<add> FileOutputStream out = new FileOutputStream(blkFile);
<add> out.write("corruption".getBytes());
<add> }
<add>
<add> // disable the heart beat from DN so that the corrupted block record is
<add> // kept in NameNode
<add> for (DataNode dn : cluster.getDataNodes()) {
<add> DataNodeTestUtils.setHeartbeatsDisabledForTests(dn, true);
<add> }
<add>
<add> // Read the file to trigger reportBadBlocks
<ide> try {
<del> Configuration conf = new HdfsConfiguration();
<del> int dataBlocks = ErasureCodingPolicyManager
<del> .getSystemDefaultPolicy().getNumDataUnits();
<del> int parityBlocks = ErasureCodingPolicyManager
<del> .getSystemDefaultPolicy().getNumParityUnits();
<del> int cellSize = ErasureCodingPolicyManager
<del> .getSystemDefaultPolicy().getCellSize();
<del> int totalSize = dataBlocks + parityBlocks;
<del> cluster = new MiniDFSCluster.Builder(conf)
<del> .numDataNodes(totalSize).build();
<del> fs = cluster.getFileSystem();
<del> Map<Integer, Integer> dnIndices = new HashMap<>();
<del> ArrayList<DataNode> dnList = cluster.getDataNodes();
<del> for (int i = 0; i < totalSize; i++) {
<del> dnIndices.put(dnList.get(i).getIpcPort(), i);
<del> }
<del>
<del> // create file
<del> Path ecDirPath = new Path("/striped");
<del> fs.mkdir(ecDirPath, FsPermission.getDirDefault());
<del> fs.getClient().setErasureCodingPolicy(ecDirPath.toString(), null);
<del> Path file = new Path(ecDirPath, "corrupted");
<del> final int length = cellSize * dataBlocks;
<del> final byte[] bytes = StripedFileTestUtil.generateBytes(length);
<del> DFSTestUtil.writeFile(fs, file, bytes);
<del>
<del> LocatedStripedBlock lsb = (LocatedStripedBlock)fs.getClient()
<del> .getLocatedBlocks(file.toString(), 0, cellSize * dataBlocks).get(0);
<del> final LocatedBlock[] blks = StripedBlockUtil.parseStripedBlockGroup(lsb,
<del> cellSize, dataBlocks, parityBlocks);
<del>
<del> // make an unrecoverable ec file with corrupted blocks
<del> for(int i = 0; i < parityBlocks + 1; i++) {
<del> int ipcPort = blks[i].getLocations()[0].getIpcPort();
<del> int dnIndex = dnIndices.get(ipcPort);
<del> File storageDir = cluster.getInstanceStorageDir(dnIndex, 0);
<del> File blkFile = MiniDFSCluster.getBlockFile(storageDir,
<del> blks[i].getBlock());
<del> Assert.assertTrue("Block file does not exist", blkFile.exists());
<del>
<del> FileOutputStream out = new FileOutputStream(blkFile);
<del> out.write("corruption".getBytes());
<del> }
<del>
<del> // disable the heart beat from DN so that the corrupted block record is
<del> // kept in NameNode
<del> for (DataNode dn : cluster.getDataNodes()) {
<del> DataNodeTestUtils.setHeartbeatsDisabledForTests(dn, true);
<del> }
<del>
<del> // Read the file to trigger reportBadBlocks
<del> try {
<del> IOUtils.copyBytes(fs.open(file), new IOUtils.NullOutputStream(), conf,
<del> true);
<del> } catch (IOException ie) {
<del> assertTrue(ie.getMessage().contains(
<del> "missingChunksNum=" + (parityBlocks + 1)));
<del> }
<del>
<del> waitForUnrecoverableBlockGroup(conf);
<del>
<del> String outStr = runFsck(conf, 1, true, "/");
<del> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<del> } finally {
<del> if (fs != null) {
<del> try {
<del> fs.close();
<del> } catch (Exception e) {
<del> }
<del> }
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<add> IOUtils.copyBytes(fs.open(file), new IOUtils.NullOutputStream(), conf,
<add> true);
<add> } catch (IOException ie) {
<add> assertTrue(ie.getMessage().contains(
<add> "missingChunksNum=" + (parityBlocks + 1)));
<add> }
<add>
<add> waitForUnrecoverableBlockGroup(conf);
<add>
<add> String outStr = runFsck(conf, 1, true, "/");
<add> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<ide> }
<ide>
<ide> @Test (timeout = 300000)
<ide> public void testFsckMissingECFile() throws Exception {
<del> MiniDFSCluster cluster = null;
<ide> DistributedFileSystem fs = null;
<del> try {
<del> Configuration conf = new HdfsConfiguration();
<del> int dataBlocks = ErasureCodingPolicyManager
<del> .getSystemDefaultPolicy().getNumDataUnits();
<del> int parityBlocks = ErasureCodingPolicyManager
<del> .getSystemDefaultPolicy().getNumParityUnits();
<del> int cellSize = ErasureCodingPolicyManager
<del> .getSystemDefaultPolicy().getCellSize();
<del> int totalSize = dataBlocks + parityBlocks;
<del> cluster = new MiniDFSCluster.Builder(conf)
<del> .numDataNodes(totalSize).build();
<del> fs = cluster.getFileSystem();
<del>
<del> // create file
<del> Path ecDirPath = new Path("/striped");
<del> fs.mkdir(ecDirPath, FsPermission.getDirDefault());
<del> fs.getClient().setErasureCodingPolicy(ecDirPath.toString(), null);
<del> Path file = new Path(ecDirPath, "missing");
<del> final int length = cellSize * dataBlocks;
<del> final byte[] bytes = StripedFileTestUtil.generateBytes(length);
<del> DFSTestUtil.writeFile(fs, file, bytes);
<del>
<del> // make an unrecoverable ec file with missing blocks
<del> ArrayList<DataNode> dns = cluster.getDataNodes();
<del> DatanodeID dnId;
<del> for (int i = 0; i < parityBlocks + 1; i++) {
<del> dnId = dns.get(i).getDatanodeId();
<del> cluster.stopDataNode(dnId.getXferAddr());
<del> cluster.setDataNodeDead(dnId);
<del> }
<del>
<del> waitForUnrecoverableBlockGroup(conf);
<del>
<del> String outStr = runFsck(conf, 1, true, "/", "-files", "-blocks",
<del> "-locations");
<del> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<del> assertTrue(outStr.contains("Live_repl=" + (dataBlocks - 1)));
<del> } finally {
<del> if (fs != null) {
<del> try {
<del> fs.close();
<del> } catch (Exception e) {
<del> }
<del> }
<del> if (cluster != null) {
<del> cluster.shutdown();
<del> }
<del> }
<del> }
<del>
<del> private void waitForUnrecoverableBlockGroup(Configuration conf)
<add> int dataBlocks = ErasureCodingPolicyManager
<add> .getSystemDefaultPolicy().getNumDataUnits();
<add> int parityBlocks = ErasureCodingPolicyManager
<add> .getSystemDefaultPolicy().getNumParityUnits();
<add> int cellSize = ErasureCodingPolicyManager
<add> .getSystemDefaultPolicy().getCellSize();
<add> int totalSize = dataBlocks + parityBlocks;
<add> cluster = new MiniDFSCluster.Builder(conf)
<add> .numDataNodes(totalSize).build();
<add> fs = cluster.getFileSystem();
<add>
<add> // create file
<add> Path ecDirPath = new Path("/striped");
<add> fs.mkdir(ecDirPath, FsPermission.getDirDefault());
<add> fs.getClient().setErasureCodingPolicy(ecDirPath.toString(), null);
<add> Path file = new Path(ecDirPath, "missing");
<add> final int length = cellSize * dataBlocks;
<add> final byte[] bytes = StripedFileTestUtil.generateBytes(length);
<add> DFSTestUtil.writeFile(fs, file, bytes);
<add>
<add> // make an unrecoverable ec file with missing blocks
<add> ArrayList<DataNode> dns = cluster.getDataNodes();
<add> DatanodeID dnId;
<add> for (int i = 0; i < parityBlocks + 1; i++) {
<add> dnId = dns.get(i).getDatanodeId();
<add> cluster.stopDataNode(dnId.getXferAddr());
<add> cluster.setDataNodeDead(dnId);
<add> }
<add>
<add> waitForUnrecoverableBlockGroup(conf);
<add>
<add> String outStr = runFsck(conf, 1, true, "/", "-files", "-blocks",
<add> "-locations");
<add> assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
<add> assertTrue(outStr.contains("Live_repl=" + (dataBlocks - 1)));
<add> }
<add>
<add> private void waitForUnrecoverableBlockGroup(Configuration configuration)
<ide> throws TimeoutException, InterruptedException {
<ide> GenericTestUtils.waitFor(new Supplier<Boolean>() {
<ide> @Override
<ide> try {
<ide> ByteArrayOutputStream bStream = new ByteArrayOutputStream();
<ide> PrintStream out = new PrintStream(bStream, true);
<del> ToolRunner.run(new DFSck(conf, out), new String[] {"/"});
<add> ToolRunner.run(new DFSck(configuration, out), new String[] {"/"});
<ide> String outStr = bStream.toString();
<ide> if (outStr.contains("UNRECOVERABLE BLOCK GROUPS")) {
<ide> return true;
<ide> }
<ide> } catch (Exception e) {
<del> FSImage.LOG.error("Exception caught", e);
<add> LOG.error("Exception caught", e);
<ide> Assert.fail("Caught unexpected exception.");
<ide> }
<ide> return false; |
|
JavaScript | apache-2.0 | 02edadbd15994d02b14ced729bbfe6526c04067f | 0 | matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,aperezdc/matrix-react-sdk | /*
Copyright 2015, 2016 OpenMarket 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.
*/
'use strict';
import React from 'react';
import classNames from 'classnames';
import sdk from '../../../index';
import { _t } from '../../../languageHandler';
import MatrixClientPeg from '../../../MatrixClientPeg';
import Modal from "../../../Modal";
import dis from "../../../dispatcher";
import RateLimitedFunc from '../../../ratelimitedfunc';
import * as linkify from 'linkifyjs';
import linkifyElement from 'linkifyjs/element';
import linkifyMatrix from '../../../linkify-matrix';
import AccessibleButton from '../elements/AccessibleButton';
import ManageIntegsButton from '../elements/ManageIntegsButton';
import {CancelButton} from './SimpleRoomHeader';
linkifyMatrix(linkify);
module.exports = React.createClass({
displayName: 'RoomHeader',
propTypes: {
room: React.PropTypes.object,
oobData: React.PropTypes.object,
editing: React.PropTypes.bool,
saving: React.PropTypes.bool,
inRoom: React.PropTypes.bool,
collapsedRhs: React.PropTypes.bool,
onSettingsClick: React.PropTypes.func,
onSaveClick: React.PropTypes.func,
onSearchClick: React.PropTypes.func,
onLeaveClick: React.PropTypes.func,
onCancelClick: React.PropTypes.func,
},
getDefaultProps: function() {
return {
editing: false,
inRoom: false,
onSaveClick: function() {},
onCancelClick: function() {},
};
},
componentDidMount: function() {
const cli = MatrixClientPeg.get();
cli.on("RoomState.events", this._onRoomStateEvents);
// When a room name occurs, RoomState.events is fired *before*
// room.name is updated. So we have to listen to Room.name as well as
// RoomState.events.
if (this.props.room) {
this.props.room.on("Room.name", this._onRoomNameChange);
}
},
componentDidUpdate: function() {
if (this.refs.topic) {
linkifyElement(this.refs.topic, linkifyMatrix.options);
}
},
componentWillUnmount: function() {
if (this.props.room) {
this.props.room.removeListener("Room.name", this._onRoomNameChange);
}
const cli = MatrixClientPeg.get();
if (cli) {
cli.removeListener("RoomState.events", this._onRoomStateEvents);
}
},
_onRoomStateEvents: function(event, state) {
if (!this.props.room || event.getRoomId() !== this.props.room.roomId) {
return;
}
// redisplay the room name, topic, etc.
this._rateLimitedUpdate();
},
_rateLimitedUpdate: new RateLimitedFunc(function() {
/* eslint-disable babel/no-invalid-this */
this.forceUpdate();
}, 500),
_onRoomNameChange: function(room) {
this.forceUpdate();
},
onAvatarPickerClick: function(ev) {
if (this.refs.file_label) {
this.refs.file_label.click();
}
},
onAvatarSelected: function(ev) {
const changeAvatar = this.refs.changeAvatar;
if (!changeAvatar) {
console.error("No ChangeAvatar found to upload image to!");
return;
}
changeAvatar.onFileSelected(ev).catch(function(err) {
const errMsg = (typeof err === "string") ? err : (err.error || "");
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
console.error("Failed to set avatar: " + errMsg);
Modal.createTrackedDialog('Failed to set avatar', '', ErrorDialog, {
title: _t("Error"),
description: _t("Failed to set avatar."),
});
}).done();
},
onShowRhsClick: function(ev) {
dis.dispatch({ action: 'show_right_panel' });
},
/**
* After editing the settings, get the new name for the room
*
* @return {?string} newName or undefined if we didn't let the user edit the room name
*/
getEditedName: function() {
let newName;
if (this.refs.nameEditor) {
newName = this.refs.nameEditor.getRoomName();
}
return newName;
},
/**
* After editing the settings, get the new topic for the room
*
* @return {?string} newTopic or undefined if we didn't let the user edit the room topic
*/
getEditedTopic: function() {
let newTopic;
if (this.refs.topicEditor) {
newTopic = this.refs.topicEditor.getTopic();
}
return newTopic;
},
render: function() {
const RoomAvatar = sdk.getComponent("avatars.RoomAvatar");
const ChangeAvatar = sdk.getComponent("settings.ChangeAvatar");
const TintableSvg = sdk.getComponent("elements.TintableSvg");
const EmojiText = sdk.getComponent('elements.EmojiText');
let name = null;
let searchStatus = null;
let topicElement = null;
let cancelButton = null;
let spinner = null;
let saveButton = null;
let settingsButton = null;
let canSetRoomName;
let canSetRoomAvatar;
let canSetRoomTopic;
if (this.props.editing) {
// calculate permissions. XXX: this should be done on mount or something
const userId = MatrixClientPeg.get().credentials.userId;
canSetRoomName = this.props.room.currentState.maySendStateEvent('m.room.name', userId);
canSetRoomAvatar = this.props.room.currentState.maySendStateEvent('m.room.avatar', userId);
canSetRoomTopic = this.props.room.currentState.maySendStateEvent('m.room.topic', userId);
saveButton = (
<AccessibleButton className="mx_RoomHeader_textButton" onClick={this.props.onSaveClick}>
{_t("Save")}
</AccessibleButton>
);
}
if (this.props.onCancelClick) {
cancelButton = <CancelButton onClick={this.props.onCancelClick}/>;
}
if (this.props.saving) {
const Spinner = sdk.getComponent("elements.Spinner");
spinner = <div className="mx_RoomHeader_spinner"><Spinner/></div>;
}
if (canSetRoomName) {
const RoomNameEditor = sdk.getComponent("rooms.RoomNameEditor");
name = <RoomNameEditor ref="nameEditor" room={this.props.room} />;
} else {
// don't display the search count until the search completes and
// gives us a valid (possibly zero) searchCount.
if (this.props.searchInfo &&
this.props.searchInfo.searchCount !== undefined &&
this.props.searchInfo.searchCount !== null) {
searchStatus = <div className="mx_RoomHeader_searchStatus">
{ _t("(~%(count)s results)", { count: this.props.searchInfo.searchCount }) }
</div>;
}
// XXX: this is a bit inefficient - we could just compare room.name for 'Empty room'...
let settingsHint = false;
const members = this.props.room ? this.props.room.getJoinedMembers() : undefined;
if (members) {
if (members.length === 1 && members[0].userId === MatrixClientPeg.get().credentials.userId) {
const nameEvent = this.props.room.currentState.getStateEvents('m.room.name', '');
if (!nameEvent || !nameEvent.getContent().name) {
settingsHint = true;
}
}
}
let roomName = _t("Join Room");
if (this.props.oobData && this.props.oobData.name) {
roomName = this.props.oobData.name;
} else if (this.props.room) {
roomName = this.props.room.name;
}
const emojiTextClasses = classNames('mx_RoomHeader_nametext', { mx_RoomHeader_settingsHint: settingsHint });
name =
<div className="mx_RoomHeader_name" onClick={this.props.onSettingsClick}>
<EmojiText dir="auto" element="div" className={emojiTextClasses} title={roomName}>{ roomName }</EmojiText>
{ searchStatus }
</div>;
}
if (canSetRoomTopic) {
const RoomTopicEditor = sdk.getComponent("rooms.RoomTopicEditor");
topicElement = <RoomTopicEditor ref="topicEditor" room={this.props.room} />;
} else {
let topic;
if (this.props.room) {
const ev = this.props.room.currentState.getStateEvents('m.room.topic', '');
if (ev) {
topic = ev.getContent().topic;
}
}
if (topic) {
topicElement =
<div className="mx_RoomHeader_topic" ref="topic" title={ topic } dir="auto">{ topic }</div>;
}
}
let roomAvatar = null;
if (canSetRoomAvatar) {
roomAvatar = (
<div className="mx_RoomHeader_avatarPicker">
<div onClick={ this.onAvatarPickerClick }>
<ChangeAvatar ref="changeAvatar" room={this.props.room} showUploadSection={false} width={48} height={48} />
</div>
<div className="mx_RoomHeader_avatarPicker_edit">
<label htmlFor="avatarInput" ref="file_label">
<img src="img/camera.svg"
alt={ _t("Upload avatar") } title={ _t("Upload avatar") }
width="17" height="15" />
</label>
<input id="avatarInput" type="file" onChange={ this.onAvatarSelected }/>
</div>
</div>
);
} else if (this.props.room || (this.props.oobData && this.props.oobData.name)) {
roomAvatar = (
<div onClick={this.props.onSettingsClick}>
<RoomAvatar room={this.props.room} width={48} height={48} oobData={this.props.oobData} />
</div>
);
}
if (this.props.onSettingsClick) {
settingsButton =
<AccessibleButton className="mx_RoomHeader_button" onClick={this.props.onSettingsClick} title={_t("Settings")}>
<TintableSvg src="img/icons-settings-room.svg" width="16" height="16"/>
</AccessibleButton>;
}
// var leave_button;
// if (this.props.onLeaveClick) {
// leave_button =
// <div className="mx_RoomHeader_button" onClick={this.props.onLeaveClick} title="Leave room">
// <TintableSvg src="img/leave.svg" width="26" height="20"/>
// </div>;
// }
let forgetButton;
if (this.props.onForgetClick) {
forgetButton =
<AccessibleButton className="mx_RoomHeader_button" onClick={this.props.onForgetClick} title={ _t("Forget room") }>
<TintableSvg src="img/leave.svg" width="26" height="20"/>
</AccessibleButton>;
}
let searchButton;
if (this.props.onSearchClick && this.props.inRoom) {
searchButton =
<AccessibleButton className="mx_RoomHeader_button" onClick={this.props.onSearchClick} title={ _t("Search") }>
<TintableSvg src="img/icons-search.svg" width="35" height="35"/>
</AccessibleButton>;
}
let rightPanelButtons;
if (this.props.collapsedRhs) {
rightPanelButtons =
<AccessibleButton className="mx_RoomHeader_button" onClick={this.onShowRhsClick} title={ _t('Show panel') }>
<TintableSvg src="img/maximise.svg" width="10" height="16"/>
</AccessibleButton>;
}
let rightRow;
if (!this.props.editing) {
rightRow =
<div className="mx_RoomHeader_rightRow">
{ settingsButton }
<ManageIntegsButton
roomId={this.props.room.roomId}
/>
{ forgetButton }
{ searchButton }
{ rightPanelButtons }
</div>;
}
return (
<div className={ "mx_RoomHeader " + (this.props.editing ? "mx_RoomHeader_editing" : "") }>
<div className="mx_RoomHeader_wrapper">
<div className="mx_RoomHeader_leftRow">
<div className="mx_RoomHeader_avatar">
{ roomAvatar }
</div>
<div className="mx_RoomHeader_info">
{ name }
{ topicElement }
</div>
</div>
{spinner}
{saveButton}
{cancelButton}
{rightRow}
</div>
</div>
);
},
});
| src/components/views/rooms/RoomHeader.js | /*
Copyright 2015, 2016 OpenMarket 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.
*/
'use strict';
import React from 'react';
import classNames from 'classnames';
import sdk from '../../../index';
import { _t } from '../../../languageHandler';
import MatrixClientPeg from '../../../MatrixClientPeg';
import Modal from "../../../Modal";
import dis from "../../../dispatcher";
import RateLimitedFunc from '../../../ratelimitedfunc';
import * as linkify from 'linkifyjs';
import linkifyElement from 'linkifyjs/element';
import linkifyMatrix from '../../../linkify-matrix';
import AccessibleButton from '../elements/AccessibleButton';
import ManageIntegsButton from '../elements/ManageIntegsButton';
import {CancelButton} from './SimpleRoomHeader';
linkifyMatrix(linkify);
module.exports = React.createClass({
displayName: 'RoomHeader',
propTypes: {
room: React.PropTypes.object,
oobData: React.PropTypes.object,
editing: React.PropTypes.bool,
saving: React.PropTypes.bool,
inRoom: React.PropTypes.bool,
collapsedRhs: React.PropTypes.bool,
onSettingsClick: React.PropTypes.func,
onSaveClick: React.PropTypes.func,
onSearchClick: React.PropTypes.func,
onLeaveClick: React.PropTypes.func,
onCancelClick: React.PropTypes.func,
},
getDefaultProps: function() {
return {
editing: false,
inRoom: false,
onSaveClick: function() {},
onCancelClick: function() {},
};
},
componentDidMount: function() {
const cli = MatrixClientPeg.get();
cli.on("RoomState.events", this._onRoomStateEvents);
// When a room name occurs, RoomState.events is fired *before*
// room.name is updated. So we have to listen to Room.name as well as
// RoomState.events.
if (this.props.room) {
this.props.room.on("Room.name", this._onRoomNameChange);
}
},
componentDidUpdate: function() {
if (this.refs.topic) {
linkifyElement(this.refs.topic, linkifyMatrix.options);
}
},
componentWillUnmount: function() {
if (this.props.room) {
this.props.room.removeListener("Room.name", this._onRoomNameChange);
}
const cli = MatrixClientPeg.get();
if (cli) {
cli.removeListener("RoomState.events", this._onRoomStateEvents);
}
},
_onRoomStateEvents: function(event, state) {
if (!this.props.room || event.getRoomId() !== this.props.room.roomId) {
return;
}
// redisplay the room name, topic, etc.
this._rateLimitedUpdate();
},
_rateLimitedUpdate: new RateLimitedFunc(function() {
/* eslint-disable babel/no-invalid-this */
this.forceUpdate();
}, 500),
_onRoomNameChange: function(room) {
this.forceUpdate();
},
onAvatarPickerClick: function(ev) {
if (this.refs.file_label) {
this.refs.file_label.click();
}
},
onAvatarSelected: function(ev) {
const changeAvatar = this.refs.changeAvatar;
if (!changeAvatar) {
console.error("No ChangeAvatar found to upload image to!");
return;
}
changeAvatar.onFileSelected(ev).catch(function(err) {
const errMsg = (typeof err === "string") ? err : (err.error || "");
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
console.error("Failed to set avatar: " + errMsg);
Modal.createTrackedDialog('Failed to set avatar', '', ErrorDialog, {
title: _t("Error"),
description: _t("Failed to set avatar."),
});
}).done();
},
onShowRhsClick: function(ev) {
dis.dispatch({ action: 'show_right_panel' });
},
/**
* After editing the settings, get the new name for the room
*
* @return {?string} newName or undefined if we didn't let the user edit the room name
*/
getEditedName: function() {
let newName;
if (this.refs.nameEditor) {
newName = this.refs.nameEditor.getRoomName();
}
return newName;
},
/**
* After editing the settings, get the new topic for the room
*
* @return {?string} newTopic or undefined if we didn't let the user edit the room topic
*/
getEditedTopic: function() {
let newTopic;
if (this.refs.topicEditor) {
newTopic = this.refs.topicEditor.getTopic();
}
return newTopic;
},
render: function() {
const RoomAvatar = sdk.getComponent("avatars.RoomAvatar");
const ChangeAvatar = sdk.getComponent("settings.ChangeAvatar");
const TintableSvg = sdk.getComponent("elements.TintableSvg");
const EmojiText = sdk.getComponent('elements.EmojiText');
let name = null;
let searchStatus = null;
let topicElement = null;
let cancelButton = null;
let spinner = null;
let saveButton = null;
let settingsButton = null;
let canSetRoomName;
let canSetRoomAvatar;
let canSetRoomTopic;
if (this.props.editing) {
// calculate permissions. XXX: this should be done on mount or something
const userId = MatrixClientPeg.get().credentials.userId;
canSetRoomName = this.props.room.currentState.maySendStateEvent('m.room.name', userId);
canSetRoomAvatar = this.props.room.currentState.maySendStateEvent('m.room.avatar', userId);
canSetRoomTopic = this.props.room.currentState.maySendStateEvent('m.room.topic', userId);
saveButton = (
<AccessibleButton className="mx_RoomHeader_textButton" onClick={this.props.onSaveClick}>
{_t("Save")}
</AccessibleButton>
);
}
if (this.props.onCancelClick) {
cancelButton = <CancelButton onClick={this.props.onCancelClick}/>;
}
if (this.props.saving) {
const Spinner = sdk.getComponent("elements.Spinner");
spinner = <div className="mx_RoomHeader_spinner"><Spinner/></div>;
}
if (canSetRoomName) {
const RoomNameEditor = sdk.getComponent("rooms.RoomNameEditor");
name = <RoomNameEditor ref="nameEditor" room={this.props.room} />;
} else {
// don't display the search count until the search completes and
// gives us a valid (possibly zero) searchCount.
if (this.props.searchInfo &&
this.props.searchInfo.searchCount !== undefined &&
this.props.searchInfo.searchCount !== null) {
searchStatus = <div className="mx_RoomHeader_searchStatus">
{ _t("(~%(count)s results)", { count: this.props.searchInfo.searchCount }) }
</div>;
}
// XXX: this is a bit inefficient - we could just compare room.name for 'Empty room'...
let settingsHint = false;
const members = this.props.room ? this.props.room.getJoinedMembers() : undefined;
if (members) {
if (members.length === 1 && members[0].userId === MatrixClientPeg.get().credentials.userId) {
const nameEvent = this.props.room.currentState.getStateEvents('m.room.name', '');
if (!nameEvent || !nameEvent.getContent().name) {
settingsHint = true;
}
}
}
let roomName = _t("Join Room");
if (this.props.oobData && this.props.oobData.name) {
roomName = this.props.oobData.name;
} else if (this.props.room) {
roomName = this.props.room.name;
}
const emojiTextClasses = classNames('mx_RoomHeader_nametext', { mx_RoomHeader_settingsHint: settingsHint });
name =
<div className="mx_RoomHeader_name" onClick={this.props.onSettingsClick}>
<EmojiText dir="auto" element="div" className={emojiTextClasses} title={roomName}>{ roomName }</EmojiText>
{ searchStatus }
</div>;
}
if (canSetRoomTopic) {
const RoomTopicEditor = sdk.getComponent("rooms.RoomTopicEditor");
topicElement = <RoomTopicEditor ref="topicEditor" room={this.props.room} />;
} else {
let topic;
if (this.props.room) {
const ev = this.props.room.currentState.getStateEvents('m.room.topic', '');
if (ev) {
topic = ev.getContent().topic;
}
}
if (topic) {
topicElement =
<div className="mx_RoomHeader_topic" ref="topic" title={ topic } dir="auto">{ topic }</div>;
}
}
let roomAvatar = null;
if (canSetRoomAvatar) {
roomAvatar = (
<div className="mx_RoomHeader_avatarPicker">
<div onClick={ this.onAvatarPickerClick }>
<ChangeAvatar ref="changeAvatar" room={this.props.room} showUploadSection={false} width={48} height={48} />
</div>
<div className="mx_RoomHeader_avatarPicker_edit">
<label htmlFor="avatarInput" ref="file_label">
<img src="img/camera.svg"
alt={ _t("Upload avatar") } title={ _t("Upload avatar") }
width="17" height="15" />
</label>
<input id="avatarInput" type="file" onChange={ this.onAvatarSelected }/>
</div>
</div>
);
} else if (this.props.room || (this.props.oobData && this.props.oobData.name)) {
roomAvatar = (
<div onClick={this.props.onSettingsClick}>
<RoomAvatar room={this.props.room} width={48} height={48} oobData={this.props.oobData} />
</div>
);
}
if (this.props.onSettingsClick) {
settingsButton =
<AccessibleButton className="mx_RoomHeader_button" onClick={this.props.onSettingsClick} title={_t("Settings")}>
<TintableSvg src="img/icons-settings-room.svg" width="16" height="16"/>
</AccessibleButton>;
}
// var leave_button;
// if (this.props.onLeaveClick) {
// leave_button =
// <div className="mx_RoomHeader_button" onClick={this.props.onLeaveClick} title="Leave room">
// <TintableSvg src="img/leave.svg" width="26" height="20"/>
// </div>;
// }
let forgetButton;
if (this.props.onForgetClick) {
forgetButton =
<AccessibleButton className="mx_RoomHeader_button" onClick={this.props.onForgetClick} title={ _t("Forget room") }>
<TintableSvg src="img/leave.svg" width="26" height="20"/>
</AccessibleButton>;
}
let searchButton;
if (this.props.onSearchClick && this.props.inRoom) {
searchButton =
<AccessibleButton className="mx_RoomHeader_button" onClick={this.props.onSearchClick} title={ _t("Search") }>
<TintableSvg src="img/icons-search.svg" width="35" height="35"/>
</AccessibleButton>;
}
let rightPanelButtons;
if (this.props.collapsedRhs) {
rightPanelButtons =
<AccessibleButton className="mx_RoomHeader_button" onClick={this.onShowRhsClick} title={ _t('Show panel') }>
<TintableSvg src="img/maximise.svg" width="10" height="16"/>
</AccessibleButton>;
}
let rightRow;
if (!this.props.editing) {
rightRow =
<div className="mx_RoomHeader_rightRow">
{ settingsButton }
<ManageIntegsButton
onCancelClick={this.props.onCancelClick}
roomId={this.props.room.roomId}
/>
{ forgetButton }
{ searchButton }
{ rightPanelButtons }
</div>;
}
return (
<div className={ "mx_RoomHeader " + (this.props.editing ? "mx_RoomHeader_editing" : "") }>
<div className="mx_RoomHeader_wrapper">
<div className="mx_RoomHeader_leftRow">
<div className="mx_RoomHeader_avatar">
{ roomAvatar }
</div>
<div className="mx_RoomHeader_info">
{ name }
{ topicElement }
</div>
</div>
{spinner}
{saveButton}
{cancelButton}
{rightRow}
</div>
</div>
);
},
});
| Don't bubble cancel click to room header.
| src/components/views/rooms/RoomHeader.js | Don't bubble cancel click to room header. | <ide><path>rc/components/views/rooms/RoomHeader.js
<ide> <div className="mx_RoomHeader_rightRow">
<ide> { settingsButton }
<ide> <ManageIntegsButton
<del> onCancelClick={this.props.onCancelClick}
<ide> roomId={this.props.room.roomId}
<ide> />
<ide> { forgetButton } |
|
Java | apache-2.0 | c919dcff9217ccb73045431243e273bf3c9df129 | 0 | makemyownlife/newdda-client | package com.elong.pb.newdda.client.datasource;
import com.elong.pb.newdda.client.router.rule.ShardingRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
import java.sql.*;
/**
* 支持分片的数据源 相关测试
* User: zhangyong
* Date: 2016/3/29
* Time: 20:11
* To change this template use File | Settings | File Templates.
*/
@ContextConfiguration(locations = {"/spring/spring-config-sharding-datasource.xml"})
public class ShardingDataSourceUnitTest extends AbstractTestNGSpringContextTests {
@Autowired
private ShardingDataSource shardingDataSource;
@Autowired
private ShardingRule shardingRule;
@Test
public void testShardDataSource() throws SQLException {
Connection shardingConnection = shardingDataSource.getConnection();
PreparedStatement statement = null;
ResultSet rs = null;
try {
statement = null;
rs = null;
statement = shardingConnection.prepareStatement("select * from test where id = ?");
statement.setInt(1, 1);
rs = statement.executeQuery();
while (rs.next()) {
System.out.println("结果是:" + rs.getString("id"));
}
} finally {
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
if (shardingConnection != null) {
shardingConnection.close();
}
}
}
@Test
public void testStatement() throws SQLException {
Connection shardingConnection = shardingDataSource.getConnection();
Statement statement = null;
ResultSet rs = null;
String sql = "select * from test where user_id = 1 and user_name = 'zhangyong'";
try {
statement = null;
rs = null;
statement = shardingConnection.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println("结果是:" + rs.getString("user_name"));
}
} finally {
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
if (shardingConnection != null) {
shardingConnection.close();
}
}
}
@Test
public void testUpdateStatement() throws SQLException {
Connection shardingConnection = shardingDataSource.getConnection();
Statement statement = null;
String sql = "update test set user_name = 'zhangyong03' where user_id = 1";
try {
statement = null;
statement = shardingConnection.createStatement();
int updateRow = statement.executeUpdate(sql);
System.out.println("updateRow=" + updateRow);
} finally {
if (statement != null) {
statement.close();
}
if (shardingConnection != null) {
shardingConnection.close();
}
}
}
@Test
public void testSelectAllStatement() throws SQLException {
Connection shardingConnection = shardingDataSource.getConnection();
Statement statement = null;
ResultSet rs = null;
String sql = "select * from test";
try {
statement = null;
rs = null;
statement = shardingConnection.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println("结果是:" + rs.getString("user_name"));
}
} finally {
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
if (shardingConnection != null) {
shardingConnection.close();
}
}
}
@Test
public void testPrepareStatement() throws SQLException {
Connection shardingConnection = shardingDataSource.getConnection();
PreparedStatement statement = null;
ResultSet rs = null;
String sql = "select * from test where user_id = ? ";
try {
statement = null;
rs = null;
statement = shardingConnection.prepareStatement(sql);
statement.setInt(1, 1);
rs = statement.executeQuery();
while (rs.next()) {
System.out.println("结果是:" + rs.getString("user_name"));
}
} finally {
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
if (shardingConnection != null) {
shardingConnection.close();
}
}
}
}
| src/test/java/com/elong/pb/newdda/client/datasource/ShardingDataSourceUnitTest.java | package com.elong.pb.newdda.client.datasource;
import com.elong.pb.newdda.client.router.rule.ShardingRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
import java.sql.*;
/**
* 支持分片的数据源 相关测试
* User: zhangyong
* Date: 2016/3/29
* Time: 20:11
* To change this template use File | Settings | File Templates.
*/
@ContextConfiguration(locations = {"/spring/spring-config-sharding-datasource.xml"})
public class ShardingDataSourceUnitTest extends AbstractTestNGSpringContextTests {
@Autowired
private ShardingDataSource shardingDataSource;
@Autowired
private ShardingRule shardingRule;
@Test
public void testShardDataSource() throws SQLException {
Connection shardingConnection = shardingDataSource.getConnection();
PreparedStatement statement = null;
ResultSet rs = null;
try {
statement = null;
rs = null;
statement = shardingConnection.prepareStatement("select * from test where id = ?");
statement.setInt(1, 1);
rs = statement.executeQuery();
while (rs.next()) {
System.out.println("结果是:" + rs.getString("id"));
}
} finally {
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
if (shardingConnection != null) {
shardingConnection.close();
}
}
}
@Test
public void testStatement() throws SQLException {
Connection shardingConnection = shardingDataSource.getConnection();
Statement statement = null;
ResultSet rs = null;
String sql = "select * from test where user_id = 1 and user_name = 'zhangyong'";
try {
statement = null;
rs = null;
statement = shardingConnection.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println("结果是:" + rs.getString("user_name"));
}
} finally {
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
if (shardingConnection != null) {
shardingConnection.close();
}
}
}
@Test
public void testUpdateStatement() throws SQLException {
Connection shardingConnection = shardingDataSource.getConnection();
Statement statement = null;
String sql = "update test set user_name = 'zhangyong04' where user_id = 1";
try {
statement = null;
statement = shardingConnection.createStatement();
int updateRow = statement.executeUpdate(sql);
System.out.println(updateRow);
} finally {
if (statement != null) {
statement.close();
}
if (shardingConnection != null) {
shardingConnection.close();
}
}
}
@Test
public void testSelectAllStatement() throws SQLException {
Connection shardingConnection = shardingDataSource.getConnection();
Statement statement = null;
ResultSet rs = null;
String sql = "select * from test";
try {
statement = null;
rs = null;
statement = shardingConnection.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println("结果是:" + rs.getString("user_name"));
}
} finally {
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
if (shardingConnection != null) {
shardingConnection.close();
}
}
}
@Test
public void testPrepareStatement() throws SQLException {
Connection shardingConnection = shardingDataSource.getConnection();
PreparedStatement statement = null;
ResultSet rs = null;
String sql = "select * from test where user_id = ? ";
try {
statement = null;
rs = null;
statement = shardingConnection.prepareStatement(sql);
statement.setInt(1, 1);
rs = statement.executeQuery();
while (rs.next()) {
System.out.println("结果是:" + rs.getString("user_name"));
}
} finally {
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
if (shardingConnection != null) {
shardingConnection.close();
}
}
}
}
| update 验证成功
| src/test/java/com/elong/pb/newdda/client/datasource/ShardingDataSourceUnitTest.java | update 验证成功 | <ide><path>rc/test/java/com/elong/pb/newdda/client/datasource/ShardingDataSourceUnitTest.java
<ide> public void testUpdateStatement() throws SQLException {
<ide> Connection shardingConnection = shardingDataSource.getConnection();
<ide> Statement statement = null;
<del> String sql = "update test set user_name = 'zhangyong04' where user_id = 1";
<add> String sql = "update test set user_name = 'zhangyong03' where user_id = 1";
<ide> try {
<ide> statement = null;
<ide> statement = shardingConnection.createStatement();
<ide> int updateRow = statement.executeUpdate(sql);
<del> System.out.println(updateRow);
<add> System.out.println("updateRow=" + updateRow);
<ide> } finally {
<ide> if (statement != null) {
<ide> statement.close(); |
|
Java | bsd-3-clause | 78753b28b7fce2cf109fc1690a3a2377ad6dc366 | 0 | salesforce/Argus,dilipdevaraj-sfdc/Argus-1,dilipdevaraj-sfdc/Argus-1,SalesforceEng/Argus,rajsarkapally/Argus,xizi-xu/Argus,dilipdevaraj-sfdc/Argus-1,xizi-xu/Argus,xizi-xu/Argus,salesforce/Argus,xizi-xu/Argus,dilipdevaraj-sfdc/Argus-1,rajsarkapally-sfdc/Argus,SalesforceEng/Argus,salesforce/Argus,rajsarkapally-sfdc/Argus,rajsarkapally/Argus,rajsarkapally-sfdc/Argus,rajsarkapally/Argus,salesforce/Argus,SalesforceEng/Argus,rajsarkapally/Argus,rajsarkapally/Argus,rajsarkapally-sfdc/Argus,SalesforceEng/Argus | package com.salesforce.dva.argus.service.schema;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.salesforce.dva.argus.AbstractTest;
import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.service.schema.ElasticSearchSchemaService;
/**
* This test suite tests the trie-based caching in the AbstractSchemaService class. Although we are instantiating
* ElasticSearchSchemaService object, the implemtationSpecificPut (which is part of ES Schema Service) has been
* mocked out. In essence, these tests only test the caching functionality.
*
* @author bhinav.sura
*
*/
public class AbstractSchemaServiceTest extends AbstractTest {
@Test
public void testPutEverythingCached() {
List<Metric> metrics = createRandomMetrics("test-scope", "test-metric", 10);
ElasticSearchSchemaService service = new ElasticSearchSchemaService(system.getConfiguration(), system.getServiceFactory().getMonitorService());
_enableCaching(service);
final AtomicInteger count = new AtomicInteger();
ElasticSearchSchemaService spyService = _initializeSpyService(service, count);
spyService.put(metrics);
assertTrue(count.get() == metrics.size());
spyService.put(metrics);
assertTrue(count.get() == metrics.size());
}
@Test
public void testPutPartialCached() {
List<Metric> metrics = createRandomMetrics("test-scope", "test-metric", 10);
List<Metric> newMetrics = createRandomMetrics("test-scope", "test-metric1", 5);
Set<Metric> total = new HashSet<>(metrics);
total.addAll(newMetrics);
ElasticSearchSchemaService service = new ElasticSearchSchemaService(system.getConfiguration(), system.getServiceFactory().getMonitorService());
_enableCaching(service);
final AtomicInteger count = new AtomicInteger();
ElasticSearchSchemaService spyService = _initializeSpyService(service, count);
spyService.put(metrics);
assertTrue(count.get() == metrics.size());
spyService.put(new ArrayList<>(total));
assertTrue(count.get() == total.size());
}
@Test
public void testPutNothingCached() {
List<Metric> metrics = createRandomMetrics("test-scope", "test-metric", 10);
List<Metric> newMetrics = createRandomMetrics("test-scope", "test-metric1", 5);
ElasticSearchSchemaService service = new ElasticSearchSchemaService(system.getConfiguration(), system.getServiceFactory().getMonitorService());
_enableCaching(service);
final AtomicInteger count = new AtomicInteger();
ElasticSearchSchemaService spyService = _initializeSpyService(service, count);
spyService.put(metrics);
assertTrue(count.get() == metrics.size());
spyService.put(newMetrics);
assertTrue(count.get() == metrics.size() + newMetrics.size());
}
@Test
public void testPutCachingDisabled() {
List<Metric> metrics = createRandomMetrics("test-scope", "test-metric", 10);
ElasticSearchSchemaService service = new ElasticSearchSchemaService(system.getConfiguration(), system.getServiceFactory().getMonitorService());
final AtomicInteger count = new AtomicInteger();
ElasticSearchSchemaService spyService = _initializeSpyService(service, count);
spyService.put(metrics);
assertTrue(count.get() == metrics.size());
spyService.put(metrics);
assertTrue(count.get() == metrics.size() * 2);
}
private ElasticSearchSchemaService _initializeSpyService(ElasticSearchSchemaService service, final AtomicInteger count) {
ElasticSearchSchemaService spyService = Mockito.spy(service);
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
@SuppressWarnings("unchecked")
List<Metric> metrics = List.class.cast(invocation.getArguments()[0]);
count.addAndGet(metrics.size());
return null;
}
}).when(spyService).implementationSpecificPut(Mockito.anyListOf(Metric.class));
return spyService;
}
private void _enableCaching(ElasticSearchSchemaService service) {
try {
Field field = service.getClass().getSuperclass().getDeclaredField("_cacheEnabled");
field.setAccessible(true);
field.set(service, true);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| ArgusCore/src/test/java/com/salesforce/dva/argus/service/schema/AbstractSchemaServiceTest.java | package com.salesforce.dva.argus.service.schema;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.salesforce.dva.argus.AbstractTest;
import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.service.schema.ElasticSearchSchemaService;
public class AbstractSchemaServiceTest extends AbstractTest {
@Test
public void testPutEverythingCached() {
List<Metric> metrics = createRandomMetrics("test-scope", "test-metric", 10);
ElasticSearchSchemaService service = new ElasticSearchSchemaService(system.getConfiguration(), system.getServiceFactory().getMonitorService());
_enableCaching(service);
final AtomicInteger count = new AtomicInteger();
ElasticSearchSchemaService spyService = _initializeSpyService(service, count);
spyService.put(metrics);
assertTrue(count.get() == metrics.size());
spyService.put(metrics);
assertTrue(count.get() == metrics.size());
}
@Test
public void testPutPartialCached() {
List<Metric> metrics = createRandomMetrics("test-scope", "test-metric", 10);
List<Metric> newMetrics = createRandomMetrics("test-scope", "test-metric1", 5);
Set<Metric> total = new HashSet<>(metrics);
total.addAll(newMetrics);
ElasticSearchSchemaService service = new ElasticSearchSchemaService(system.getConfiguration(), system.getServiceFactory().getMonitorService());
_enableCaching(service);
final AtomicInteger count = new AtomicInteger();
ElasticSearchSchemaService spyService = _initializeSpyService(service, count);
spyService.put(metrics);
assertTrue(count.get() == metrics.size());
spyService.put(new ArrayList<>(total));
assertTrue(count.get() == total.size());
}
@Test
public void testPutNothingCached() {
List<Metric> metrics = createRandomMetrics("test-scope", "test-metric", 10);
List<Metric> newMetrics = createRandomMetrics("test-scope", "test-metric1", 5);
ElasticSearchSchemaService service = new ElasticSearchSchemaService(system.getConfiguration(), system.getServiceFactory().getMonitorService());
_enableCaching(service);
final AtomicInteger count = new AtomicInteger();
ElasticSearchSchemaService spyService = _initializeSpyService(service, count);
spyService.put(metrics);
assertTrue(count.get() == metrics.size());
spyService.put(newMetrics);
assertTrue(count.get() == metrics.size() + newMetrics.size());
}
@Test
public void testPutCachingDisabled() {
List<Metric> metrics = createRandomMetrics("test-scope", "test-metric", 10);
ElasticSearchSchemaService service = new ElasticSearchSchemaService(system.getConfiguration(), system.getServiceFactory().getMonitorService());
final AtomicInteger count = new AtomicInteger();
ElasticSearchSchemaService spyService = _initializeSpyService(service, count);
spyService.put(metrics);
assertTrue(count.get() == metrics.size());
spyService.put(metrics);
assertTrue(count.get() == metrics.size() * 2);
}
private ElasticSearchSchemaService _initializeSpyService(ElasticSearchSchemaService service, final AtomicInteger count) {
ElasticSearchSchemaService spyService = Mockito.spy(service);
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
@SuppressWarnings("unchecked")
List<Metric> metrics = List.class.cast(invocation.getArguments()[0]);
count.addAndGet(metrics.size());
return null;
}
}).when(spyService).implementationSpecificPut(Mockito.anyListOf(Metric.class));
return spyService;
}
private void _enableCaching(ElasticSearchSchemaService service) {
try {
Field field = service.getClass().getSuperclass().getDeclaredField("_cacheEnabled");
field.setAccessible(true);
field.set(service, true);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| Add javadoc for AbstractSchemaServiceTest.java
| ArgusCore/src/test/java/com/salesforce/dva/argus/service/schema/AbstractSchemaServiceTest.java | Add javadoc for AbstractSchemaServiceTest.java | <ide><path>rgusCore/src/test/java/com/salesforce/dva/argus/service/schema/AbstractSchemaServiceTest.java
<ide> import com.salesforce.dva.argus.entity.Metric;
<ide> import com.salesforce.dva.argus.service.schema.ElasticSearchSchemaService;
<ide>
<add>
<add>/**
<add> * This test suite tests the trie-based caching in the AbstractSchemaService class. Although we are instantiating
<add> * ElasticSearchSchemaService object, the implemtationSpecificPut (which is part of ES Schema Service) has been
<add> * mocked out. In essence, these tests only test the caching functionality.
<add> *
<add> * @author bhinav.sura
<add> *
<add> */
<ide> public class AbstractSchemaServiceTest extends AbstractTest {
<ide>
<ide> @Test |
|
Java | epl-1.0 | 9a106d5379442494228e5c57e3e60c460d3db6e5 | 0 | rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,sguan-actuate/birt,sguan-actuate/birt | /*
*************************************************************************
* Copyright (c) 2005, 2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.report.data.oda.sampledb.ui.profile;
import java.util.Properties;
import org.eclipse.birt.report.data.oda.jdbc.ui.util.Constants;
import org.eclipse.birt.report.data.oda.sampledb.SampleDBConstants;
import org.eclipse.birt.report.data.oda.sampledb.SampleDBJDBCConnectionFactory;
import org.eclipse.birt.report.data.oda.sampledb.ui.i18n.Messages;
import org.eclipse.datatools.connectivity.oda.util.manifest.ConnectionProfileProperty;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PlatformUI;
/**
* Helper class to create sampleDb selection page and property page
*
*/
public class SampleDbSelectionPageHelper
{
private WizardPage m_wizardPage;
private PreferencePage m_propertyPage;
private static final String SAMPLE_DB_SCHEMA="ClassicModels";
private final String CONEXT_ID_DATASOURCE_SAMPLEDB = "org.eclipse.birt.cshelp.Wizard_DatasourceProfile_ID";//$NON-NLS-1$
private Label m_driverClass, m_driverURL, m_sampleUser;
static final String DEFAULT_MESSAGE =
Messages.getMessage( "datasource.page.title" ); //$NON-NLS-1$
private static final String EMPTY_STRING = "";
SampleDbSelectionPageHelper( WizardPage page )
{
m_wizardPage = page;
}
SampleDbSelectionPageHelper( PreferencePage page )
{
m_propertyPage = page;
}
void createCustomControl( Composite parent )
{
// create the composite to hold the widgets
Composite content = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.numColumns = 2;
content.setLayout( layout );
new Label( content, SWT.LEFT ).setText( Messages.getMessage( "datasource.page.driver.class" ) ); //$NON-NLS-1$
m_driverClass = new Label( content, SWT.LEFT );
m_driverClass.setText( SampleDBConstants.DRIVER_CLASS ); //$NON-NLS-1$
new Label( content, SWT.LEFT ).setText( Messages.getMessage( "datasource.page.url" ) ); //$NON-NLS-1$
m_driverURL = new Label( content, SWT.LEFT );
m_driverURL.setText( SampleDBConstants.DRIVER_URL );//$NON-NLS-1$
new Label( content, SWT.LEFT ).setText( Messages.getMessage( "datasource.page.user" ) ); //$NON-NLS-1$
m_sampleUser = new Label( content, SWT.LEFT );
m_sampleUser.setText( SampleDBJDBCConnectionFactory.getDbUser( ) );//$NON-NLS-1$
setMessage( DEFAULT_MESSAGE );
PlatformUI.getWorkbench( ).getHelpSystem( ).setHelp( content,
CONEXT_ID_DATASOURCE_SAMPLEDB );
}
/**
* collect custom properties
*
* @param props
* @return
*/
Properties collectCustomProperties( Properties props )
{
if( props == null )
props = new Properties();
// set custom driver specific properties
props.setProperty( Constants.ODADriverClass, getDriverClass( ) );
props.setProperty( Constants.ODAURL, getDriverUrl( ) );
props.setProperty( Constants.ODAUser, SAMPLE_DB_SCHEMA );
props.setProperty( Constants.ODAPassword, "" );
// sampledb uses predined connection property values, and does not support
// external reference to a connection profile
props.setProperty( ConnectionProfileProperty.PROFILE_NAME_PROP_KEY, "" );
props.setProperty( ConnectionProfileProperty.PROFILE_STORE_FILE_PATH_PROP_KEY, "" );
return props;
}
/**
* get driver class
* @return
*/
private String getDriverClass( )
{
return SampleDBConstants.DRIVER_CLASS;
}
/**
* get driver url
* @return
*/
private String getDriverUrl( )
{
// TODO Auto-generated method stub
return SampleDBConstants.DRIVER_URL;
}
/**
* populate initial properties
* @param profileProps
*/
void initCustomControl( Properties profileProps )
{
if( profileProps == null || profileProps.isEmpty() )
return; // nothing to initialize
String driverClass = profileProps.getProperty( Constants.ODADriverClass );
if( driverClass == null )
driverClass = EMPTY_STRING;
m_driverClass.setText( driverClass );
String driverUrl = profileProps.getProperty( Constants.ODAURL );
if( driverUrl == null )
driverUrl = EMPTY_STRING;
m_driverURL.setText( driverUrl );
String user = profileProps.getProperty( Constants.ODAUser );
if( user == null )
user = EMPTY_STRING;
m_sampleUser.setText( user );
}
/**
* set message
* @param message
*/
private void setMessage( String message )
{
if ( m_wizardPage != null )
m_wizardPage.setMessage( message );
else if ( m_propertyPage != null )
m_propertyPage.setMessage( message );
}
/**
* set message
* @param message
* @param type
*/
private void setMessage( String message, int type )
{
if ( m_wizardPage != null )
m_wizardPage.setMessage( message, type );
else if ( m_propertyPage != null )
m_propertyPage.setMessage( message, type );
}
}
| data/org.eclipse.birt.report.data.oda.sampledb.ui/src/org/eclipse/birt/report/data/oda/sampledb/ui/profile/SampleDbSelectionPageHelper.java | /*
*************************************************************************
* Copyright (c) 2005, 2006 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.report.data.oda.sampledb.ui.profile;
import java.util.Properties;
import org.eclipse.birt.report.data.oda.jdbc.ui.util.Constants;
import org.eclipse.birt.report.data.oda.sampledb.SampleDBConstants;
import org.eclipse.birt.report.data.oda.sampledb.SampleDBJDBCConnectionFactory;
import org.eclipse.birt.report.data.oda.sampledb.ui.i18n.Messages;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PlatformUI;
/**
* Helper class to create sampleDb selection page and property page
*
*/
public class SampleDbSelectionPageHelper
{
private WizardPage m_wizardPage;
private PreferencePage m_propertyPage;
private static final String SAMPLE_DB_SCHEMA="ClassicModels";
private final String CONEXT_ID_DATASOURCE_SAMPLEDB = "org.eclipse.birt.cshelp.Wizard_DatasourceProfile_ID";//$NON-NLS-1$
private Label m_driverClass, m_driverURL, m_sampleUser;
static final String DEFAULT_MESSAGE =
Messages.getMessage( "datasource.page.title" ); //$NON-NLS-1$
private static final String EMPTY_STRING = "";
SampleDbSelectionPageHelper( WizardPage page )
{
m_wizardPage = page;
}
SampleDbSelectionPageHelper( PreferencePage page )
{
m_propertyPage = page;
}
void createCustomControl( Composite parent )
{
// create the composite to hold the widgets
Composite content = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.numColumns = 2;
content.setLayout( layout );
new Label( content, SWT.LEFT ).setText( Messages.getMessage( "datasource.page.driver.class" ) ); //$NON-NLS-1$
m_driverClass = new Label( content, SWT.LEFT );
m_driverClass.setText( SampleDBConstants.DRIVER_CLASS ); //$NON-NLS-1$
new Label( content, SWT.LEFT ).setText( Messages.getMessage( "datasource.page.url" ) ); //$NON-NLS-1$
m_driverURL = new Label( content, SWT.LEFT );
m_driverURL.setText( SampleDBConstants.DRIVER_URL );//$NON-NLS-1$
new Label( content, SWT.LEFT ).setText( Messages.getMessage( "datasource.page.user" ) ); //$NON-NLS-1$
m_sampleUser = new Label( content, SWT.LEFT );
m_sampleUser.setText( SampleDBJDBCConnectionFactory.getDbUser( ) );//$NON-NLS-1$
setMessage( DEFAULT_MESSAGE );
PlatformUI.getWorkbench( ).getHelpSystem( ).setHelp( content,
CONEXT_ID_DATASOURCE_SAMPLEDB );
}
/**
* collect custom properties
*
* @param props
* @return
*/
Properties collectCustomProperties( Properties props )
{
if( props == null )
props = new Properties();
// set custom driver specific properties
props.setProperty( Constants.ODADriverClass, getDriverClass( ) );
props.setProperty( Constants.ODAURL, getDriverUrl( ) );
props.setProperty( Constants.ODAUser, SAMPLE_DB_SCHEMA );
props.setProperty( Constants.ODAPassword, "" );
return props;
}
/**
* get driver class
* @return
*/
private String getDriverClass( )
{
return SampleDBConstants.DRIVER_CLASS;
}
/**
* get driver url
* @return
*/
private String getDriverUrl( )
{
// TODO Auto-generated method stub
return SampleDBConstants.DRIVER_URL;
}
/**
* populate initial properties
* @param profileProps
*/
void initCustomControl( Properties profileProps )
{
if( profileProps == null || profileProps.isEmpty() )
return; // nothing to initialize
String driverClass = profileProps.getProperty( Constants.ODADriverClass );
if( driverClass == null )
driverClass = EMPTY_STRING;
m_driverClass.setText( driverClass );
String driverUrl = profileProps.getProperty( Constants.ODAURL );
if( driverUrl == null )
driverUrl = EMPTY_STRING;
m_driverURL.setText( driverUrl );
String user = profileProps.getProperty( Constants.ODAUser );
if( user == null )
user = EMPTY_STRING;
m_sampleUser.setText( user );
}
/**
* set message
* @param message
*/
private void setMessage( String message )
{
if ( m_wizardPage != null )
m_wizardPage.setMessage( message );
else if ( m_propertyPage != null )
m_propertyPage.setMessage( message );
}
/**
* set message
* @param message
* @param type
*/
private void setMessage( String message, int type )
{
if ( m_wizardPage != null )
m_wizardPage.setMessage( message, type );
else if ( m_propertyPage != null )
m_propertyPage.setMessage( message, type );
}
}
| [183104] Override connection profile properties to not save reference to a conn profile, which does not match its saved identity as an oda.jdbc extension
| data/org.eclipse.birt.report.data.oda.sampledb.ui/src/org/eclipse/birt/report/data/oda/sampledb/ui/profile/SampleDbSelectionPageHelper.java | [183104] Override connection profile properties to not save reference to a conn profile, which does not match its saved identity as an oda.jdbc extension | <ide><path>ata/org.eclipse.birt.report.data.oda.sampledb.ui/src/org/eclipse/birt/report/data/oda/sampledb/ui/profile/SampleDbSelectionPageHelper.java
<ide> /*
<ide> *************************************************************************
<del> * Copyright (c) 2005, 2006 Actuate Corporation.
<add> * Copyright (c) 2005, 2007 Actuate Corporation.
<ide> * All rights reserved. This program and the accompanying materials
<ide> * are made available under the terms of the Eclipse Public License v1.0
<ide> * which accompanies this distribution, and is available at
<ide> import org.eclipse.birt.report.data.oda.sampledb.SampleDBConstants;
<ide> import org.eclipse.birt.report.data.oda.sampledb.SampleDBJDBCConnectionFactory;
<ide> import org.eclipse.birt.report.data.oda.sampledb.ui.i18n.Messages;
<add>import org.eclipse.datatools.connectivity.oda.util.manifest.ConnectionProfileProperty;
<ide> import org.eclipse.jface.preference.PreferencePage;
<ide> import org.eclipse.jface.wizard.WizardPage;
<ide> import org.eclipse.swt.SWT;
<ide> props.setProperty( Constants.ODAURL, getDriverUrl( ) );
<ide> props.setProperty( Constants.ODAUser, SAMPLE_DB_SCHEMA );
<ide> props.setProperty( Constants.ODAPassword, "" );
<add>
<add> // sampledb uses predined connection property values, and does not support
<add> // external reference to a connection profile
<add> props.setProperty( ConnectionProfileProperty.PROFILE_NAME_PROP_KEY, "" );
<add> props.setProperty( ConnectionProfileProperty.PROFILE_STORE_FILE_PATH_PROP_KEY, "" );
<add>
<ide> return props;
<ide> }
<ide> |
|
JavaScript | mit | 4ec0985fbd5db2dacf803aa55b8f7b14b7919d41 | 0 | ntilwalli/cyclejs,feliciousx-open-source/cyclejs,maskinoshita/cyclejs,usm4n/cyclejs,ntilwalli/cyclejs,staltz/cycle,usm4n/cyclejs,feliciousx-open-source/cyclejs,usm4n/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cyclejs,maskinoshita/cyclejs,cyclejs/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cyclejs,ntilwalli/cyclejs,cyclejs/cyclejs,maskinoshita/cyclejs,maskinoshita/cyclejs,usm4n/cyclejs,staltz/cycle,cyclejs/cycle-core,cyclejs/cycle-core,ntilwalli/cyclejs | 'use strict';
/* global describe, it */
var assert = require('assert');
var src = require('../lib/index');
var Rx = require('rxjs');
var Cycle = require('@cycle/rxjs-run').default;
var makeHTTPDriver = src.makeHTTPDriver;
function run(uri) {
describe('makeHTTPDriver', function () {
it('should be a driver factory', function () {
assert.strictEqual(typeof makeHTTPDriver, 'function');
var output = makeHTTPDriver();
assert.strictEqual(typeof output, 'function');
});
});
describe('HTTP Driver', function () {
this.timeout(8000);
it('should throw when request stream emits neither string nor object',
function (done) {
function main(sources) {
return {
HTTP: Rx.Observable.of(123)
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
output.sources.HTTP.select().mergeAll().subscribe(
function next() { assert.fail(); },
function error(err) {
assert.strictEqual(err.message, 'Observable of requests given to ' +
'HTTP Driver must emit either URL strings or objects with ' +
'parameters.'
);
done();
},
function complete() { assert.fail(); }
);
output.run();
}
);
it('should throw when given options object without url string',
function (done) {
function main() {
return {
HTTP: Rx.Observable.of({ method: 'post' })
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
output.sources.HTTP.select().mergeAll().subscribe(
function next() { assert.fail(); },
function error(err) {
assert.strictEqual(
err.message, 'Please provide a `url` property in the request ' +
'options.'
);
done();
},
function complete() { assert.fail(); }
);
output.run();
}
);
it('should return response metastream when given a simple URL string',
function (done) {
function main() {
return {
HTTP: Rx.Observable.of(uri + '/hello')
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
output.sources.HTTP.select().subscribe(function (response$) {
assert.strictEqual(typeof response$.request, 'object');
assert.strictEqual(response$.request.url, uri + '/hello');
response$.subscribe(function (response) {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.text, 'Hello World');
done();
});
});
output.run();
}
);
it('should return HTTPSource with isolateSource and isolateSink',
function (done) {
function main() {
return {
HTTP: Rx.Observable.of(uri + '/hello')
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
output.run();
var httpSource = output.sources.HTTP;
assert.strictEqual(typeof httpSource.isolateSource, 'function');
assert.strictEqual(typeof httpSource.isolateSink, 'function');
done();
}
);
it('should return response metastream when given simple options obj',
function (done) {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/pet',
method: 'POST',
send: { name: 'Woof', species: 'Dog' }
})
};
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$.subscribe(function (response$) {
assert.strictEqual(response$.request.url, uri + '/pet');
assert.strictEqual(response$.request.method, 'POST');
assert.strictEqual(response$.request.send.name, 'Woof');
assert.strictEqual(response$.request.send.species, 'Dog');
response$.subscribe(function (response) {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.text, 'added Woof the Dog');
done();
});
});
output.run();
}
);
it('should have DevTools flag in select() source stream', function (done) {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/pet',
method: 'POST',
send: { name: 'Woof', species: 'Dog' }
})
};
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
assert.strictEqual(response$$._isCycleSource, 'HTTP');
done();
output.run();
});
it('should have DevTools flag in response$$ source stream', function (done) {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/pet',
method: 'POST',
send: { name: 'Woof', species: 'Dog' }
})
};
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
assert.strictEqual(response$$._isCycleSource, 'HTTP');
done();
output.run();
});
it('should return response metastream when given another options obj',
function (done) {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/querystring',
method: 'GET',
query: { foo: 102030, bar: 'Pub' }
})
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$.subscribe(function (response$) {
assert.strictEqual(response$.request.url, uri + '/querystring');
assert.strictEqual(response$.request.method, 'GET');
assert.strictEqual(response$.request.query.foo, 102030);
assert.strictEqual(response$.request.query.bar, 'Pub');
response$.subscribe(function (response) {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.body.foo, '102030');
assert.strictEqual(response.body.bar, 'Pub');
done();
});
});
output.run();
}
);
it('should return response metastream when given yet another options obj',
function (done) {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/delete',
method: 'DELETE',
query: { foo: 102030, bar: 'Pub' }
})
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$.subscribe(function (response$) {
assert.strictEqual(response$.request.url, uri + '/delete');
assert.strictEqual(response$.request.method, 'DELETE');
response$.subscribe(function (response) {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.body.deleted, true);
done();
});
});
output.run();
}
);
it('should not be possible to change the metastream\'s request',
function () {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/hello',
method: 'GET'
})
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$
.map(function (response$) {
response$.request = 1234;
return response$;
})
.subscribe(function next(response$) {
assert.fail();
}, function error(err) {
assert.strictEqual(err instanceof TypeError, true);
});
output.run();
}
)
it('should send 500 server errors to response$ onError',
function (done) {
function main() {
return {
HTTP: Rx.Observable.of(uri + '/error')
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$.subscribe(function (response$) {
assert.strictEqual(typeof response$.request, 'object');
assert.strictEqual(response$.request.url, uri + '/error');
response$.subscribe(
function next() { assert.fail(); },
function error(err) {
assert.strictEqual(err.status, 500);
assert.strictEqual(err.message, 'Internal Server Error');
assert.strictEqual(err.response.text, 'boom');
done();
},
function complete() { assert.fail(); }
);
});
output.run();
}
);
it('should not be sensitive to ordering of sinks (issue #476)', function (done) {
function main(sources) {
var request$ = Rx.Observable.of({
url: uri + '/hello',
method: 'GET',
});
var response$ = sources.HTTP.select()
.mergeAll()
.map(function (res) { return res.text; });
// Notice HTTP comes before Test here. This is crucial for this test.
return {
HTTP: request$,
Test: response$,
}
}
var testDriverExpected = ['Hello World'];
function testDriver(sink) {
sink.subscribe(function (x) {
assert.strictEqual(testDriverExpected.length, 1);
assert.strictEqual(x, testDriverExpected.shift());
assert.strictEqual(testDriverExpected.length, 0);
done();
});
}
var output = Cycle(main, {
HTTP: makeHTTPDriver(),
Test: testDriver,
});
output.run();
});
it('should have the request object on the response$ onError stream',
function (done) {
function main() {
return {
HTTP: Rx.Observable.of(uri + '/error')
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$.subscribe(function (response$) {
assert.strictEqual(typeof response$.request, 'object');
assert.strictEqual(response$.request.url, uri + '/error');
response$.subscribe(
function next() { assert.fail(); },
function error(err) {
assert.strictEqual(typeof err.response.request, 'object');
assert.strictEqual(err.response.request.url, uri + '/error');
done();
},
function complete() { assert.fail(); }
);
});
output.run();
}
);
});
describe('isolateSource and isolateSink', function () {
it('should exist on the HTTPSource', function (done) {
function main() {
return {
HTTP: new Rx.Subject()
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var httpSource = output.sources.HTTP;
assert.strictEqual(typeof httpSource.isolateSource, 'function');
assert.strictEqual(typeof httpSource.isolateSink, 'function');
done();
});
it('should exist on a scoped HTTPSource', function (done) {
function main() {
return {
HTTP: new Rx.Subject()
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var httpSource = output.sources.HTTP;
var scopedHTTPSource = httpSource.isolateSource(httpSource, 'foo');
assert.strictEqual(typeof scopedHTTPSource.isolateSource, 'function');
assert.strictEqual(typeof scopedHTTPSource.isolateSink, 'function');
done();
});
it('should hide responses from outside the scope',
function (done) {
var proxyRequest$ = new Rx.Subject();
function main() {
return {
HTTP: proxyRequest$
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var httpSource = output.sources.HTTP;
var ignoredRequest$ = Rx.Observable.of(uri + '/json');
var request$ = Rx.Observable.of(uri + '/hello').delay(10);
var scopedRequest$ = httpSource.isolateSink(request$, 'foo');
var scopedHTTPSource = httpSource.isolateSource(httpSource, 'foo');
scopedHTTPSource.select().subscribe(function (response$) {
assert.strictEqual(typeof response$.request, 'object');
assert.strictEqual(response$.request.url, uri + '/hello');
response$.subscribe(function (response) {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.text, 'Hello World');
done();
});
});
Rx.Observable.merge(ignoredRequest$, scopedRequest$)
.subscribe(proxyRequest$);
output.run();
}
);
});
}
module.exports = run;
| http/test/common.js | 'use strict';
/* global describe, it */
var assert = require('assert');
var src = require('../lib/index');
var Rx = require('rxjs');
var Cycle = require('@cycle/rxjs-run').default;
var makeHTTPDriver = src.makeHTTPDriver;
function run(uri) {
describe('makeHTTPDriver', function () {
it('should be a driver factory', function () {
assert.strictEqual(typeof makeHTTPDriver, 'function');
var output = makeHTTPDriver();
assert.strictEqual(typeof output, 'function');
});
});
describe('HTTP Driver', function () {
this.timeout(8000);
it('should throw when request stream emits neither string nor object',
function(done) {
function main(sources) {
return {
HTTP: Rx.Observable.of(123)
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
output.sources.HTTP.select().mergeAll().subscribe(
function next() { assert.fail(); },
function error(err) {
assert.strictEqual(err.message, 'Observable of requests given to ' +
'HTTP Driver must emit either URL strings or objects with ' +
'parameters.'
);
done();
},
function complete() { assert.fail(); }
);
output.run();
}
);
it('should throw when given options object without url string',
function(done) {
function main() {
return {
HTTP: Rx.Observable.of({method: 'post'})
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
output.sources.HTTP.select().mergeAll().subscribe(
function next() { assert.fail(); },
function error(err) {
assert.strictEqual(
err.message, 'Please provide a `url` property in the request ' +
'options.'
);
done();
},
function complete() { assert.fail(); }
);
output.run();
}
);
it('should return response metastream when given a simple URL string',
function(done) {
function main() {
return {
HTTP: Rx.Observable.of(uri + '/hello')
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
output.sources.HTTP.select().subscribe(function(response$) {
assert.strictEqual(typeof response$.request, 'object');
assert.strictEqual(response$.request.url, uri + '/hello');
response$.subscribe(function(response) {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.text, 'Hello World');
done();
});
});
output.run();
}
);
it('should return HTTPSource with isolateSource and isolateSink',
function(done) {
function main() {
return {
HTTP: Rx.Observable.of(uri + '/hello')
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
output.run();
var httpSource = output.sources.HTTP;
assert.strictEqual(typeof httpSource.isolateSource, 'function');
assert.strictEqual(typeof httpSource.isolateSink, 'function');
done();
}
);
it('should return response metastream when given simple options obj',
function(done) {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/pet',
method: 'POST',
send: {name: 'Woof', species: 'Dog'}
})
};
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$.subscribe(function(response$) {
assert.strictEqual(response$.request.url, uri + '/pet');
assert.strictEqual(response$.request.method, 'POST');
assert.strictEqual(response$.request.send.name, 'Woof');
assert.strictEqual(response$.request.send.species, 'Dog');
response$.subscribe(function(response) {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.text, 'added Woof the Dog');
done();
});
});
output.run();
}
);
it('should have DevTools flag in select() source stream', function(done) {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/pet',
method: 'POST',
send: {name: 'Woof', species: 'Dog'}
})
};
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
assert.strictEqual(response$$._isCycleSource, 'HTTP');
done();
output.run();
});
it('should have DevTools flag in response$$ source stream', function(done) {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/pet',
method: 'POST',
send: {name: 'Woof', species: 'Dog'}
})
};
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
assert.strictEqual(response$$._isCycleSource, 'HTTP');
done();
output.run();
});
it('should return response metastream when given another options obj',
function(done) {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/querystring',
method: 'GET',
query: {foo: 102030, bar: 'Pub'}
})
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$.subscribe(function(response$) {
assert.strictEqual(response$.request.url, uri + '/querystring');
assert.strictEqual(response$.request.method, 'GET');
assert.strictEqual(response$.request.query.foo, 102030);
assert.strictEqual(response$.request.query.bar, 'Pub');
response$.subscribe(function(response) {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.body.foo, '102030');
assert.strictEqual(response.body.bar, 'Pub');
done();
});
});
output.run();
}
);
it('should return response metastream when given yet another options obj',
function(done) {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/delete',
method: 'DELETE',
query: {foo: 102030, bar: 'Pub'}
})
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$.subscribe(function(response$) {
assert.strictEqual(response$.request.url, uri + '/delete');
assert.strictEqual(response$.request.method, 'DELETE');
response$.subscribe(function(response) {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.body.deleted, true);
done();
});
});
output.run();
}
);
it('should not be possible to change the metastream\'s request',
function () {
function main() {
return {
HTTP: Rx.Observable.of({
url: uri + '/hello',
method: 'GET'
})
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$
.map(function (response$) {
response$.request = 1234;
return response$;
})
.subscribe(function next(response$) {
assert.fail();
}, function error(err) {
assert.strictEqual(err instanceof TypeError, true);
});
output.run();
}
)
it('should send 500 server errors to response$ onError',
function(done) {
function main() {
return {
HTTP: Rx.Observable.of(uri + '/error')
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var response$$ = output.sources.HTTP.select();
response$$.subscribe(function(response$) {
assert.strictEqual(typeof response$.request, 'object');
assert.strictEqual(response$.request.url, uri + '/error');
response$.subscribe(
function next() { assert.fail(); },
function error(err) {
assert.strictEqual(err.status, 500);
assert.strictEqual(err.message, 'Internal Server Error');
assert.strictEqual(err.response.text, 'boom');
done();
},
function complete() { assert.fail(); }
);
});
output.run();
}
);
it('should not be sensitive to ordering of sinks (issue #476)', function(done) {
function main(sources) {
var request$ = Rx.Observable.of({
url: uri + '/hello',
method: 'GET',
});
var response$ = sources.HTTP.select()
.mergeAll()
.map(function (res) { return res.text; });
// Notice HTTP comes before Test here. This is crucial for this test.
return {
HTTP: request$,
Test: response$,
}
}
var testDriverExpected = ['Hello World'];
function testDriver(sink) {
sink.subscribe(function (x) {
assert.strictEqual(testDriverExpected.length, 1);
assert.strictEqual(x, testDriverExpected.shift());
assert.strictEqual(testDriverExpected.length, 0);
done();
});
}
var output = Cycle(main, {
HTTP: makeHTTPDriver(),
Test: testDriver,
});
output.run();
});
});
describe('isolateSource and isolateSink', function () {
it('should exist on the HTTPSource', function(done) {
function main() {
return {
HTTP: new Rx.Subject()
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var httpSource = output.sources.HTTP;
assert.strictEqual(typeof httpSource.isolateSource, 'function');
assert.strictEqual(typeof httpSource.isolateSink, 'function');
done();
});
it('should exist on a scoped HTTPSource', function(done) {
function main() {
return {
HTTP: new Rx.Subject()
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var httpSource = output.sources.HTTP;
var scopedHTTPSource = httpSource.isolateSource(httpSource, 'foo');
assert.strictEqual(typeof scopedHTTPSource.isolateSource, 'function');
assert.strictEqual(typeof scopedHTTPSource.isolateSink, 'function');
done();
});
it('should hide responses from outside the scope',
function(done) {
var proxyRequest$ = new Rx.Subject();
function main() {
return {
HTTP: proxyRequest$
}
}
var output = Cycle(main, { HTTP: makeHTTPDriver() });
var httpSource = output.sources.HTTP;
var ignoredRequest$ = Rx.Observable.of(uri + '/json');
var request$ = Rx.Observable.of(uri + '/hello').delay(10);
var scopedRequest$ = httpSource.isolateSink(request$, 'foo');
var scopedHTTPSource = httpSource.isolateSource(httpSource, 'foo');
scopedHTTPSource.select().subscribe(function(response$) {
assert.strictEqual(typeof response$.request, 'object');
assert.strictEqual(response$.request.url, uri + '/hello');
response$.subscribe(function(response) {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.text, 'Hello World');
done();
});
});
Rx.Observable.merge(ignoredRequest$, scopedRequest$)
.subscribe(proxyRequest$);
output.run();
}
);
});
}
module.exports = run;
| test(http): added test to ensure request object is available on http err response
| http/test/common.js | test(http): added test to ensure request object is available on http err response | <ide><path>ttp/test/common.js
<ide> this.timeout(8000);
<ide>
<ide> it('should throw when request stream emits neither string nor object',
<del> function(done) {
<add> function (done) {
<ide> function main(sources) {
<ide> return {
<ide> HTTP: Rx.Observable.of(123)
<ide> );
<ide>
<ide> it('should throw when given options object without url string',
<del> function(done) {
<del> function main() {
<del> return {
<del> HTTP: Rx.Observable.of({method: 'post'})
<add> function (done) {
<add> function main() {
<add> return {
<add> HTTP: Rx.Observable.of({ method: 'post' })
<ide> }
<ide> }
<ide> var output = Cycle(main, { HTTP: makeHTTPDriver() });
<ide> );
<ide>
<ide> it('should return response metastream when given a simple URL string',
<del> function(done) {
<add> function (done) {
<ide> function main() {
<ide> return {
<ide> HTTP: Rx.Observable.of(uri + '/hello')
<ide>
<ide> var output = Cycle(main, { HTTP: makeHTTPDriver() });
<ide>
<del> output.sources.HTTP.select().subscribe(function(response$) {
<add> output.sources.HTTP.select().subscribe(function (response$) {
<ide> assert.strictEqual(typeof response$.request, 'object');
<ide> assert.strictEqual(response$.request.url, uri + '/hello');
<del> response$.subscribe(function(response) {
<add> response$.subscribe(function (response) {
<ide> assert.strictEqual(response.status, 200);
<ide> assert.strictEqual(response.text, 'Hello World');
<ide> done();
<ide> );
<ide>
<ide> it('should return HTTPSource with isolateSource and isolateSink',
<del> function(done) {
<add> function (done) {
<ide> function main() {
<ide> return {
<ide> HTTP: Rx.Observable.of(uri + '/hello')
<ide> );
<ide>
<ide> it('should return response metastream when given simple options obj',
<del> function(done) {
<add> function (done) {
<ide> function main() {
<ide> return {
<ide> HTTP: Rx.Observable.of({
<ide> url: uri + '/pet',
<ide> method: 'POST',
<del> send: {name: 'Woof', species: 'Dog'}
<add> send: { name: 'Woof', species: 'Dog' }
<ide> })
<ide> };
<ide> }
<ide> var output = Cycle(main, { HTTP: makeHTTPDriver() });
<ide>
<ide> var response$$ = output.sources.HTTP.select();
<del> response$$.subscribe(function(response$) {
<add> response$$.subscribe(function (response$) {
<ide> assert.strictEqual(response$.request.url, uri + '/pet');
<ide> assert.strictEqual(response$.request.method, 'POST');
<ide> assert.strictEqual(response$.request.send.name, 'Woof');
<ide> assert.strictEqual(response$.request.send.species, 'Dog');
<del> response$.subscribe(function(response) {
<add> response$.subscribe(function (response) {
<ide> assert.strictEqual(response.status, 200);
<ide> assert.strictEqual(response.text, 'added Woof the Dog');
<ide> done();
<ide> }
<ide> );
<ide>
<del> it('should have DevTools flag in select() source stream', function(done) {
<add> it('should have DevTools flag in select() source stream', function (done) {
<ide> function main() {
<ide> return {
<ide> HTTP: Rx.Observable.of({
<ide> url: uri + '/pet',
<ide> method: 'POST',
<del> send: {name: 'Woof', species: 'Dog'}
<add> send: { name: 'Woof', species: 'Dog' }
<ide> })
<ide> };
<ide> }
<ide> output.run();
<ide> });
<ide>
<del> it('should have DevTools flag in response$$ source stream', function(done) {
<add> it('should have DevTools flag in response$$ source stream', function (done) {
<ide> function main() {
<ide> return {
<ide> HTTP: Rx.Observable.of({
<ide> url: uri + '/pet',
<ide> method: 'POST',
<del> send: {name: 'Woof', species: 'Dog'}
<add> send: { name: 'Woof', species: 'Dog' }
<ide> })
<ide> };
<ide> }
<ide> });
<ide>
<ide> it('should return response metastream when given another options obj',
<del> function(done) {
<add> function (done) {
<ide> function main() {
<ide> return {
<ide> HTTP: Rx.Observable.of({
<ide> url: uri + '/querystring',
<ide> method: 'GET',
<del> query: {foo: 102030, bar: 'Pub'}
<add> query: { foo: 102030, bar: 'Pub' }
<ide> })
<ide> }
<ide> }
<ide> var output = Cycle(main, { HTTP: makeHTTPDriver() });
<ide>
<ide> var response$$ = output.sources.HTTP.select();
<del> response$$.subscribe(function(response$) {
<add> response$$.subscribe(function (response$) {
<ide> assert.strictEqual(response$.request.url, uri + '/querystring');
<ide> assert.strictEqual(response$.request.method, 'GET');
<ide> assert.strictEqual(response$.request.query.foo, 102030);
<ide> assert.strictEqual(response$.request.query.bar, 'Pub');
<del> response$.subscribe(function(response) {
<add> response$.subscribe(function (response) {
<ide> assert.strictEqual(response.status, 200);
<ide> assert.strictEqual(response.body.foo, '102030');
<ide> assert.strictEqual(response.body.bar, 'Pub');
<ide> );
<ide>
<ide> it('should return response metastream when given yet another options obj',
<del> function(done) {
<add> function (done) {
<ide> function main() {
<ide> return {
<ide> HTTP: Rx.Observable.of({
<ide> url: uri + '/delete',
<ide> method: 'DELETE',
<del> query: {foo: 102030, bar: 'Pub'}
<add> query: { foo: 102030, bar: 'Pub' }
<ide> })
<ide> }
<ide> }
<ide> var output = Cycle(main, { HTTP: makeHTTPDriver() });
<ide> var response$$ = output.sources.HTTP.select();
<ide>
<del> response$$.subscribe(function(response$) {
<add> response$$.subscribe(function (response$) {
<ide> assert.strictEqual(response$.request.url, uri + '/delete');
<ide> assert.strictEqual(response$.request.method, 'DELETE');
<del> response$.subscribe(function(response) {
<add> response$.subscribe(function (response) {
<ide> assert.strictEqual(response.status, 200);
<ide> assert.strictEqual(response.body.deleted, true);
<ide> done();
<ide> )
<ide>
<ide> it('should send 500 server errors to response$ onError',
<del> function(done) {
<add> function (done) {
<ide> function main() {
<ide> return {
<ide> HTTP: Rx.Observable.of(uri + '/error')
<ide> var output = Cycle(main, { HTTP: makeHTTPDriver() });
<ide> var response$$ = output.sources.HTTP.select();
<ide>
<del> response$$.subscribe(function(response$) {
<add> response$$.subscribe(function (response$) {
<ide> assert.strictEqual(typeof response$.request, 'object');
<ide> assert.strictEqual(response$.request.url, uri + '/error');
<ide> response$.subscribe(
<ide> }
<ide> );
<ide>
<del> it('should not be sensitive to ordering of sinks (issue #476)', function(done) {
<add> it('should not be sensitive to ordering of sinks (issue #476)', function (done) {
<ide> function main(sources) {
<ide> var request$ = Rx.Observable.of({
<ide> url: uri + '/hello',
<ide> });
<ide> output.run();
<ide> });
<add>
<add> it('should have the request object on the response$ onError stream',
<add> function (done) {
<add> function main() {
<add> return {
<add> HTTP: Rx.Observable.of(uri + '/error')
<add> }
<add> }
<add>
<add> var output = Cycle(main, { HTTP: makeHTTPDriver() });
<add> var response$$ = output.sources.HTTP.select();
<add> response$$.subscribe(function (response$) {
<add> assert.strictEqual(typeof response$.request, 'object');
<add> assert.strictEqual(response$.request.url, uri + '/error');
<add> response$.subscribe(
<add> function next() { assert.fail(); },
<add> function error(err) {
<add> assert.strictEqual(typeof err.response.request, 'object');
<add> assert.strictEqual(err.response.request.url, uri + '/error');
<add> done();
<add> },
<add> function complete() { assert.fail(); }
<add> );
<add> });
<add> output.run();
<add> }
<add> );
<ide> });
<ide>
<ide> describe('isolateSource and isolateSink', function () {
<del> it('should exist on the HTTPSource', function(done) {
<add> it('should exist on the HTTPSource', function (done) {
<ide> function main() {
<ide> return {
<ide> HTTP: new Rx.Subject()
<ide> done();
<ide> });
<ide>
<del> it('should exist on a scoped HTTPSource', function(done) {
<add> it('should exist on a scoped HTTPSource', function (done) {
<ide> function main() {
<ide> return {
<ide> HTTP: new Rx.Subject()
<ide> });
<ide>
<ide> it('should hide responses from outside the scope',
<del> function(done) {
<add> function (done) {
<ide> var proxyRequest$ = new Rx.Subject();
<ide> function main() {
<ide> return {
<ide> var scopedRequest$ = httpSource.isolateSink(request$, 'foo');
<ide> var scopedHTTPSource = httpSource.isolateSource(httpSource, 'foo');
<ide>
<del> scopedHTTPSource.select().subscribe(function(response$) {
<add> scopedHTTPSource.select().subscribe(function (response$) {
<ide> assert.strictEqual(typeof response$.request, 'object');
<ide> assert.strictEqual(response$.request.url, uri + '/hello');
<del> response$.subscribe(function(response) {
<add> response$.subscribe(function (response) {
<ide> assert.strictEqual(response.status, 200);
<ide> assert.strictEqual(response.text, 'Hello World');
<ide> done(); |
|
Java | mit | 4589e0b1eb63110bd584849e84e43ae9ffea0c67 | 0 | min90/Positioning | package dk.ubicomp.positioning;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.kontakt.sdk.android.ble.connection.OnServiceReadyListener;
import com.kontakt.sdk.android.ble.manager.ProximityManager;
import com.kontakt.sdk.android.ble.manager.ProximityManagerFactory;
import com.kontakt.sdk.android.ble.manager.listeners.IBeaconListener;
import com.kontakt.sdk.android.ble.manager.listeners.simple.SimpleIBeaconListener;
import com.kontakt.sdk.android.common.KontaktSDK;
import com.kontakt.sdk.android.common.profile.IBeaconDevice;
import com.kontakt.sdk.android.common.profile.IBeaconRegion;
import com.mapspeople.data.OnDataReadyListener;
import com.mapspeople.mapcontrol.MapControl;
import com.mapspeople.models.AppConfig;
import com.mapspeople.models.CategoryCollection;
import com.mapspeople.models.Point;
import com.mapspeople.models.PushMessageCollection;
import com.mapspeople.models.Solution;
import com.mapspeople.models.VenueCollection;
import com.google.android.gms.maps.model.LatLng;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import Utilities.BeaconLocation;
import Utilities.FindLocationByBeacon;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Jesper on 10/03/2017.
*/
public class MapFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMarkerClickListener, com.google.android.gms.location.LocationListener,
GoogleMap.OnInfoWindowClickListener, OnDataReadyListener {
private static final String DEBUG_TAG = MapFragment.class.getSimpleName();
private static final int PERMISSION_FINE_LOCATION_CODE = 101;
//Beacons
private static int REQUEST_ENABLE_BT = 1;
private ProximityManager proximityManager;
private ArrayList<IBeaconDevice> beacons = new ArrayList<>();
private boolean useBT = false;
@BindView(R.id.map_view)
MapView mapView;
private GoogleApiClient mGoogleApiClient;
private Location lastKnownLocation;
private GoogleMap mGoogleMap;
private MapControl mapControl;
private ArrayList<Beacon> parsedBeacons;
private ArrayList<Geometry> geom;
private Marker userBTLocation;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
ButterKnife.bind(this, view);
setHasOptionsMenu(true);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
mapControl = new MapControl(getActivity(), mapView);
mapControl.setOnDataReadyListener(this);
mapControl.initMap("55cdde212a91e0049824fe86", "sdu");
connectToGoogleAPI();
GeometryData geometryData = new GeometryData(getActivity());
parsedBeacons = geometryData.parseBeacons();
Log.d(DEBUG_TAG, "beacons " + parsedBeacons.toString());
geom = geometryData.parseOULocations();
Log.d(DEBUG_TAG, "Geometry: " + geom.toString());
//Beacons
//Check bluetooth on device
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
//Enable bluetooth if not enabled
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}else {
listenForBluetooth();
}
}
return view;
}
private void listenForBluetooth() {
Log.d(DEBUG_TAG, "Started listening for bluetooth");
KontaktSDK.initialize("qslWWgrHTjrQIcJWBfLnIPfyohnvKhfS");
proximityManager = ProximityManagerFactory.create(getActivity());
proximityManager.setIBeaconListener(createIBeaconListener());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuInflater menuInflater = getActivity().getMenuInflater();
menuInflater.inflate(R.menu.map_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(DEBUG_TAG, "hello");
switch (item.getItemId()) {
case R.id.explorer_update:
Toast.makeText(getActivity(), "Switching to indoor", Toast.LENGTH_SHORT).show();
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void connectToGoogleAPI() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
private void moveCamera(GoogleMap mGoogleMap, int zoomLevel, LatLng latLng) {
if (mGoogleMap != null) {
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(makeInitialZoom(latLng, zoomLevel)));
return;
}
Toast.makeText(getActivity(), "Kortet fejlede, prøv igen!", Toast.LENGTH_SHORT).show();
}
private CameraPosition makeInitialZoom(LatLng latLng, int zoomLevel) {
return new CameraPosition.Builder()
.target(latLng)
.zoom(zoomLevel)
.build();
}
@Override
public void onStart() {
super.onStart();
if (mGoogleApiClient != null) mGoogleApiClient.connect();
startScanning();
}
@Override
public void onResume() {
if (mapView != null) mapView.onResume();
super.onResume();
}
@Override
public void onPause() {
if (mapView != null) mapView.onPause();
super.onPause();
}
@Override
public void onStop() {
super.onStop();
if (mGoogleApiClient != null) mGoogleApiClient.disconnect();
proximityManager.stopScanning();
}
@Override
public void onDestroy() {
if (mapView != null) mapView.onDestroy();
proximityManager.disconnect();
proximityManager = null;
super.onDestroy();
}
@Override
public void onLowMemory() {
if (mapView != null) mapView.onLowMemory();
super.onLowMemory();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void initGoogleMapInstance() {
if (mGoogleMap != null) {
try {
mGoogleMap.setMyLocationEnabled(true);
} catch (SecurityException ex) {
Log.e(DEBUG_TAG, "The Fine location permission were not granted", ex);
}
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_FINE_LOCATION_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // If the request is cancelled the grantResults array is empty so we check for higher than zero.
initGoogleMapInstance();
} else {
Toast.makeText(getActivity(), "Permission to access fine location were not granted!", Toast.LENGTH_LONG).show();
FragmentTransactioner.get().returnToHome(getActivity());
}
return;
}
}
@Override
public void onInfoWindowClick(Marker marker) {
}
@Override
public void onLocationDataReady() {
}
@Override
public void onAppDataReady() {
}
@Override
public void onVenueDataReady(VenueCollection venueCollection) {
}
@Override
public void onSolutionDataReady(Solution solution) {
}
@Override
public void onCategoryDataReady(CategoryCollection categoryCollection) {
}
@Override
public void onPushMessageDataReady(PushMessageCollection pushMessageCollection) {
}
@Override
public void onAppConfigDataReady(AppConfig appConfig) {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION_CODE);
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_FINE_LOCATION_CODE);
return;
}
//lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
//Point pos = new Point(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
//mapControl.setMapPosition(pos, true);
//moveCamera(mGoogleMap, 17, new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()));
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public boolean onMarkerClick(Marker marker) {
return false;
}
private void startScanning() {
proximityManager.connect(new OnServiceReadyListener() {
@Override
public void onServiceReady() {
Log.d(DEBUG_TAG, "ProxyMgr started scanning!");
proximityManager.startScanning();
}
});
}
// Use a marker for user location
// Use snapping where we look at the strength of the signal (RSSI)
// So if room U165 is the strongest we snap to that room
// Update beacons every 5 sec.
private IBeaconListener createIBeaconListener() {
return new SimpleIBeaconListener() {
@Override
public void onIBeaconDiscovered(IBeaconDevice ibeacon, IBeaconRegion region) {
Log.d(DEBUG_TAG, "IBeacon discovered: " + ibeacon.toString());
beacons.add(ibeacon);
printBeacons();
IBeaconDevice beaconDevice = getHighestRSSI();
Location userLocation = findLocationBySnapping(beaconDevice);
if(userLocation != null) {
if(userBTLocation != null)
userBTLocation.remove();
userBTLocation = mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
.title("Bluetooth location by snapping"));
moveCamera(mGoogleMap, 20, new LatLng(userLocation.getLatitude(), userLocation.getLongitude()));
}
}
@Override
public void onIBeaconsUpdated(List<IBeaconDevice> iBeacons, IBeaconRegion region) {
Log.d("Sample", "Beacons updated size: " + iBeacons.size());
beacons = new ArrayList<>(iBeacons);
printBeacons();
IBeaconDevice beaconDevice = getHighestRSSI();
Location userLocation = findLocationBySnapping(beaconDevice);
if(userLocation != null) {
if(userBTLocation != null)
userBTLocation.remove();
userBTLocation = mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
.title("Bluetooth location by snapping"));
moveCamera(mGoogleMap, 20, new LatLng(userLocation.getLatitude(), userLocation.getLongitude()));
}
}
@Override
public void onIBeaconLost(IBeaconDevice iBeacon, IBeaconRegion region) {
Log.d("Sample", "Beacon lost: " + iBeacon.toString());
beacons.remove(iBeacon);
}
};
}
private IBeaconDevice getHighestRSSI() {
IBeaconDevice maxBeacon = null;
for (IBeaconDevice beacon : beacons) {
if(maxBeacon == null || maxBeacon.getRssi() > beacon.getRssi()) {
maxBeacon = beacon;
}
Log.d(DEBUG_TAG, "Beacon: " + beacon.getRssi());
}
return maxBeacon;
}
private Location findLocationBySnapping(IBeaconDevice iBeacon){
String roomAlias = iBeacon.getUniqueId();
ArrayList<LatLng> latlngs = new ArrayList();
Location userLocation = new Location(roomAlias);
double latitude = 0.0;
double longitude = 0.0;
//Find ibeacon room
String room = "";
for (Beacon b : parsedBeacons) {
if(b.getAlias().equals(roomAlias))
room = b.getRoomId();
}
for (int i=0; i<geom.size(); i++){
if (geom.get(i).getRoomId().equals(room))
latlngs = geom.get(i).getCoordinates();
}
if(latlngs.size() == 0 || room == "")
return null;
for (LatLng latlng: latlngs) {
latitude += latlng.latitude;
longitude += latlng.longitude;
}
longitude = longitude/latlngs.size();
latitude = latitude/latlngs.size();
userLocation.setLongitude(longitude);
userLocation.setLatitude(latitude);
return userLocation;
}
private void printBeacons() {
Log.i(DEBUG_TAG, "Beacon list:");
for (IBeaconDevice beacon : beacons) {
Log.d(DEBUG_TAG, "Beacon: " + beacon.getRssi());
Log.i(DEBUG_TAG, beacon.toString());
}
}
private Location findLocationByLateration(ArrayList<IBeaconDevice> b) {
if(b.size() >= 3) {
Location beaconA = BeaconLocation.getBeaconLocation(b.get(0));
Location beaconB = BeaconLocation.getBeaconLocation(b.get(1));
Location beaconC = BeaconLocation.getBeaconLocation(b.get(2));
return FindLocationByBeacon.getLocationWithTrilateration(
beaconA,
beaconB,
beaconC,
FindLocationByBeacon.getRssiAsMeters(b.get(0).getRssi()),
FindLocationByBeacon.getRssiAsMeters(b.get(1).getRssi()),
FindLocationByBeacon.getRssiAsMeters(b.get(2).getRssi())
);
} else {
return null;
}
}
//For bluetooth
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == getActivity().RESULT_OK) {
listenForBluetooth();
} else {
//finish();
}
}
}
}
| app/src/main/java/dk/ubicomp/positioning/MapFragment.java | package dk.ubicomp.positioning;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.kontakt.sdk.android.ble.connection.OnServiceReadyListener;
import com.kontakt.sdk.android.ble.manager.ProximityManager;
import com.kontakt.sdk.android.ble.manager.ProximityManagerFactory;
import com.kontakt.sdk.android.ble.manager.listeners.IBeaconListener;
import com.kontakt.sdk.android.ble.manager.listeners.simple.SimpleIBeaconListener;
import com.kontakt.sdk.android.common.KontaktSDK;
import com.kontakt.sdk.android.common.profile.IBeaconDevice;
import com.kontakt.sdk.android.common.profile.IBeaconRegion;
import com.mapspeople.data.OnDataReadyListener;
import com.mapspeople.mapcontrol.MapControl;
import com.mapspeople.models.AppConfig;
import com.mapspeople.models.CategoryCollection;
import com.mapspeople.models.Point;
import com.mapspeople.models.PushMessageCollection;
import com.mapspeople.models.Solution;
import com.mapspeople.models.VenueCollection;
import com.google.android.gms.maps.model.LatLng;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import Utilities.BeaconLocation;
import Utilities.FindLocationByBeacon;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Jesper on 10/03/2017.
*/
public class MapFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMarkerClickListener, com.google.android.gms.location.LocationListener,
GoogleMap.OnInfoWindowClickListener, OnDataReadyListener {
private static final String DEBUG_TAG = MapFragment.class.getSimpleName();
private static final int PERMISSION_FINE_LOCATION_CODE = 101;
//Beacons
private static int REQUEST_ENABLE_BT = 1;
private ProximityManager proximityManager;
private ArrayList<IBeaconDevice> beacons = new ArrayList<>();
private boolean useBT = false;
@BindView(R.id.map_view)
MapView mapView;
private GoogleApiClient mGoogleApiClient;
private Location lastKnownLocation;
private GoogleMap mGoogleMap;
private MapControl mapControl;
private ArrayList<Beacon> parsedBeacons;
private ArrayList<Geometry> geom;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
ButterKnife.bind(this, view);
setHasOptionsMenu(true);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
mapControl = new MapControl(getActivity(), mapView);
mapControl.setOnDataReadyListener(this);
mapControl.initMap("55cdde212a91e0049824fe86", "sdu");
connectToGoogleAPI();
GeometryData geometryData = new GeometryData(getActivity());
parsedBeacons = geometryData.parseBeacons();
Log.d(DEBUG_TAG, "beacons " + parsedBeacons.toString());
geom = geometryData.parseOULocations();
Log.d(DEBUG_TAG, "Geometry: " + geom.toString());
//Beacons
//Check bluetooth on device
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
//Enable bluetooth if not enabled
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}else {
listenForBluetooth();
}
}
return view;
}
private void listenForBluetooth() {
Log.d(DEBUG_TAG, "Started listening for bluetooth");
KontaktSDK.initialize("qslWWgrHTjrQIcJWBfLnIPfyohnvKhfS");
proximityManager = ProximityManagerFactory.create(getActivity());
proximityManager.setIBeaconListener(createIBeaconListener());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuInflater menuInflater = getActivity().getMenuInflater();
menuInflater.inflate(R.menu.map_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(DEBUG_TAG, "hello");
switch (item.getItemId()) {
case R.id.explorer_update:
Toast.makeText(getActivity(), "Switching to indoor", Toast.LENGTH_SHORT).show();
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void connectToGoogleAPI() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
private void moveCamera(GoogleMap mGoogleMap, int zoomLevel, LatLng latLng) {
if (mGoogleMap != null) {
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(makeInitialZoom(latLng, zoomLevel)));
return;
}
Toast.makeText(getActivity(), "Kortet fejlede, prøv igen!", Toast.LENGTH_SHORT).show();
}
private CameraPosition makeInitialZoom(LatLng latLng, int zoomLevel) {
return new CameraPosition.Builder()
.target(latLng)
.zoom(zoomLevel)
.build();
}
@Override
public void onStart() {
super.onStart();
if (mGoogleApiClient != null) mGoogleApiClient.connect();
startScanning();
}
@Override
public void onResume() {
if (mapView != null) mapView.onResume();
super.onResume();
}
@Override
public void onPause() {
if (mapView != null) mapView.onPause();
super.onPause();
}
@Override
public void onStop() {
super.onStop();
if (mGoogleApiClient != null) mGoogleApiClient.disconnect();
proximityManager.stopScanning();
}
@Override
public void onDestroy() {
if (mapView != null) mapView.onDestroy();
proximityManager.disconnect();
proximityManager = null;
super.onDestroy();
}
@Override
public void onLowMemory() {
if (mapView != null) mapView.onLowMemory();
super.onLowMemory();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void initGoogleMapInstance() {
if (mGoogleMap != null) {
try {
mGoogleMap.setMyLocationEnabled(true);
} catch (SecurityException ex) {
Log.e(DEBUG_TAG, "The Fine location permission were not granted", ex);
}
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_FINE_LOCATION_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // If the request is cancelled the grantResults array is empty so we check for higher than zero.
initGoogleMapInstance();
} else {
Toast.makeText(getActivity(), "Permission to access fine location were not granted!", Toast.LENGTH_LONG).show();
FragmentTransactioner.get().returnToHome(getActivity());
}
return;
}
}
@Override
public void onInfoWindowClick(Marker marker) {
}
@Override
public void onLocationDataReady() {
}
@Override
public void onAppDataReady() {
}
@Override
public void onVenueDataReady(VenueCollection venueCollection) {
}
@Override
public void onSolutionDataReady(Solution solution) {
}
@Override
public void onCategoryDataReady(CategoryCollection categoryCollection) {
}
@Override
public void onPushMessageDataReady(PushMessageCollection pushMessageCollection) {
}
@Override
public void onAppConfigDataReady(AppConfig appConfig) {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION_CODE);
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_FINE_LOCATION_CODE);
return;
}
//lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
//Point pos = new Point(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
//mapControl.setMapPosition(pos, true);
//moveCamera(mGoogleMap, 17, new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()));
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public boolean onMarkerClick(Marker marker) {
return false;
}
private void startScanning() {
proximityManager.connect(new OnServiceReadyListener() {
@Override
public void onServiceReady() {
Log.d(DEBUG_TAG, "ProxyMgr started scanning!");
proximityManager.startScanning();
}
});
}
// Use a marker for user location
// Use snapping where we look at the strength of the signal (RSSI)
// So if room U165 is the strongest we snap to that room
// Update beacons every 5 sec.
private IBeaconListener createIBeaconListener() {
return new SimpleIBeaconListener() {
@Override
public void onIBeaconDiscovered(IBeaconDevice ibeacon, IBeaconRegion region) {
Log.d(DEBUG_TAG, "IBeacon discovered: " + ibeacon.toString());
beacons.add(ibeacon);
printBeacons();
IBeaconDevice beaconDevice = getHighestRSSI();
Location userLocation = findLocationByLateration(beacons);
if(userLocation != null) {
Log.i(DEBUG_TAG, userLocation.toString());
mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
.title("Bluetooth location"));
moveCamera(mGoogleMap, 20, new LatLng(userLocation.getLatitude(), userLocation.getLongitude()));
}
}
@Override
public void onIBeaconsUpdated(List<IBeaconDevice> iBeacons, IBeaconRegion region) {
Log.d("Sample", "Beacons updated size: " + iBeacons.size());
beacons = new ArrayList<>(iBeacons);
printBeacons();
IBeaconDevice beaconDevice = getHighestRSSI();
Location userLocation = findLocationByLateration(beacons);
if(userLocation != null)
Log.i(DEBUG_TAG, userLocation.toString());
}
@Override
public void onIBeaconLost(IBeaconDevice iBeacon, IBeaconRegion region) {
Log.d("Sample", "Beacon lost: " + iBeacon.toString());
beacons.remove(iBeacon);
printBeacons();
IBeaconDevice beaconDevice = getHighestRSSI();
Location userLocation = findLocationByLateration(beacons);
if(userLocation != null)
Log.i(DEBUG_TAG, userLocation.toString());
}
};
}
private IBeaconDevice getHighestRSSI() {
IBeaconDevice maxBeacon = null;
for (IBeaconDevice beacon : beacons) {
if(maxBeacon == null || maxBeacon.getRssi() > beacon.getRssi()) {
maxBeacon = beacon;
}
Log.d(DEBUG_TAG, "Beacon: " + beacon.getRssi());
}
return maxBeacon;
}
/*
private Location findLocationBySnapping(IBeaconDevice iBeacon){
String roomAlias = iBeacon.getUniqueId();
ArrayList<Latlng> latlngs;
for (int i=0; i<geom.size(); i++){
latlngs.add(i, geom.get(i).getCoordinates());
}
return userLocation;
}*/
private void printBeacons() {
Log.i(DEBUG_TAG, "Beacon list:");
for (IBeaconDevice beacon : beacons) {
Log.d(DEBUG_TAG, "Beacon: " + beacon.getRssi());
Log.i(DEBUG_TAG, beacon.toString());
}
}
private Location findLocationByLateration(ArrayList<IBeaconDevice> b) {
if(b.size() >= 3) {
Location beaconA = BeaconLocation.getBeaconLocation(b.get(0));
Location beaconB = BeaconLocation.getBeaconLocation(b.get(1));
Location beaconC = BeaconLocation.getBeaconLocation(b.get(2));
return FindLocationByBeacon.getLocationWithTrilateration(
beaconA,
beaconB,
beaconC,
FindLocationByBeacon.getRssiAsMeters(b.get(0).getRssi()),
FindLocationByBeacon.getRssiAsMeters(b.get(1).getRssi()),
FindLocationByBeacon.getRssiAsMeters(b.get(2).getRssi())
);
} else {
return null;
}
}
//For bluetooth
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == getActivity().RESULT_OK) {
listenForBluetooth();
} else {
//finish();
}
}
}
}
| Now works as intended
| app/src/main/java/dk/ubicomp/positioning/MapFragment.java | Now works as intended | <ide><path>pp/src/main/java/dk/ubicomp/positioning/MapFragment.java
<ide>
<ide> private ArrayList<Beacon> parsedBeacons;
<ide> private ArrayList<Geometry> geom;
<del>
<add> private Marker userBTLocation;
<ide> @Nullable
<ide> @Override
<ide> public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
<ide> printBeacons();
<ide> IBeaconDevice beaconDevice = getHighestRSSI();
<ide>
<del> Location userLocation = findLocationByLateration(beacons);
<add> Location userLocation = findLocationBySnapping(beaconDevice);
<ide> if(userLocation != null) {
<del> Log.i(DEBUG_TAG, userLocation.toString());
<del> mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
<del> .title("Bluetooth location"));
<add> if(userBTLocation != null)
<add> userBTLocation.remove();
<add> userBTLocation = mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
<add> .title("Bluetooth location by snapping"));
<ide> moveCamera(mGoogleMap, 20, new LatLng(userLocation.getLatitude(), userLocation.getLongitude()));
<ide> }
<ide>
<ide> printBeacons();
<ide> IBeaconDevice beaconDevice = getHighestRSSI();
<ide>
<del> Location userLocation = findLocationByLateration(beacons);
<del> if(userLocation != null)
<del> Log.i(DEBUG_TAG, userLocation.toString());
<add> Location userLocation = findLocationBySnapping(beaconDevice);
<add> if(userLocation != null) {
<add> if(userBTLocation != null)
<add> userBTLocation.remove();
<add> userBTLocation = mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
<add> .title("Bluetooth location by snapping"));
<add> moveCamera(mGoogleMap, 20, new LatLng(userLocation.getLatitude(), userLocation.getLongitude()));
<add> }
<add>
<ide>
<ide> }
<ide> @Override
<ide> public void onIBeaconLost(IBeaconDevice iBeacon, IBeaconRegion region) {
<ide> Log.d("Sample", "Beacon lost: " + iBeacon.toString());
<ide> beacons.remove(iBeacon);
<del> printBeacons();
<del> IBeaconDevice beaconDevice = getHighestRSSI();
<del> Location userLocation = findLocationByLateration(beacons);
<del> if(userLocation != null)
<del> Log.i(DEBUG_TAG, userLocation.toString());
<ide> }
<ide> };
<ide> }
<ide> }
<ide> return maxBeacon;
<ide> }
<del>/*
<add>
<ide> private Location findLocationBySnapping(IBeaconDevice iBeacon){
<ide> String roomAlias = iBeacon.getUniqueId();
<del> ArrayList<Latlng> latlngs;
<add> ArrayList<LatLng> latlngs = new ArrayList();
<add> Location userLocation = new Location(roomAlias);
<add> double latitude = 0.0;
<add> double longitude = 0.0;
<add> //Find ibeacon room
<add> String room = "";
<add> for (Beacon b : parsedBeacons) {
<add> if(b.getAlias().equals(roomAlias))
<add> room = b.getRoomId();
<add> }
<ide>
<ide> for (int i=0; i<geom.size(); i++){
<del> latlngs.add(i, geom.get(i).getCoordinates());
<del> }
<del>
<add> if (geom.get(i).getRoomId().equals(room))
<add> latlngs = geom.get(i).getCoordinates();
<add> }
<add>
<add> if(latlngs.size() == 0 || room == "")
<add> return null;
<add>
<add> for (LatLng latlng: latlngs) {
<add> latitude += latlng.latitude;
<add> longitude += latlng.longitude;
<add> }
<add>
<add> longitude = longitude/latlngs.size();
<add> latitude = latitude/latlngs.size();
<add>
<add> userLocation.setLongitude(longitude);
<add> userLocation.setLatitude(latitude);
<ide> return userLocation;
<del> }*/
<add> }
<ide>
<ide> private void printBeacons() {
<ide> Log.i(DEBUG_TAG, "Beacon list:"); |
|
Java | mit | 9cfd2e29ef2dbaaf54f92c795186b1d562a5efdb | 0 | caizixian/algorithm_exercise,caizixian/algorithm_exercise,caizixian/algorithm_exercise,caizixian/algorithm_exercise,caizixian/algorithm_exercise | import java.util.Arrays;
import java.util.HashSet;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
class Pair {
final Integer x;
final Integer y;
final int idx1;
final int idx2;
Pair(int x, int y) {
this.x = Math.min(x, y);
this.y = Math.max(x, y);
this.idx1 = 0;
this.idx2 = 0;
}
Pair(int x, int y, int idx1, int idx2) {
this.x = Math.min(x, y);
this.y = Math.max(x, y);
this.idx1 = idx1;
this.idx2 = idx2;
}
public boolean conficts(int i) {
return i == idx1 || i == idx2;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
return other.x.equals(this.x) && other.y.equals(this.y);
}
public int hashCode() {
return x.hashCode() * 31 + y.hashCode();
}
}
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new LinkedList<>();
HashMap<Integer, HashSet<Pair>> sum = new HashMap<>();
for (int i = 0; i < nums.length - 1; i++) {
if (i != 0 && nums[i - 1] == nums[i]) {
continue;
}
for (int j = i + 1; j < nums.length; j++) {
if (j != i + 1 && nums[j - 1] == nums[j]) {
continue;
}
sum.putIfAbsent(nums[i] + nums[j], new HashSet<>());
sum.get(nums[i] + nums[j]).add(new Pair(nums[i], nums[j], i, j));
}
}
HashSet<Pair> used = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (i != nums.length - 1 && nums[i] == nums[i + 1]) {
continue;
}
int n = nums[i];
if (sum.containsKey(-n)) {
HashSet<Pair> idxPair = sum.get(-n);
for (Pair p : idxPair) {
Pair dup_check = new Pair(Math.min(n, p.x), Math.max(n, p.y));
if (!p.conficts(i) && !used.contains(dup_check)) {
LinkedList<Integer> combination = new LinkedList<>();
combination.add(n);
combination.add(p.x);
combination.add(p.y);
result.add(combination);
used.add(dup_check);
}
}
}
}
return result;
}
} | LeetCode/15.3Sum.java | import java.util.Arrays;
import java.util.HashSet;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
class Pair {
final Integer x;
final Integer y;
final int idx1;
final int idx2;
Pair(int x, int y) {
this.x = Math.min(x, y);
this.y = Math.max(x, y);
this.idx1 = 0;
this.idx2 = 0;
}
Pair(int x, int y, int idx1, int idx2) {
this.x = Math.min(x, y);
this.y = Math.max(x, y);
this.idx1 = idx1;
this.idx2 = idx2;
}
public boolean conficts(int i) {
return i == idx1 || i == idx2;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
return other.x.equals(this.x) && other.y.equals(this.y);
}
public int hashCode() {
return x.hashCode() * 31 + y.hashCode();
}
public String toString() {
return x + " " + y + " " + idx1 + " " + idx2;
}
}
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new LinkedList<>();
HashMap<Integer, HashSet<Pair>> sum = new HashMap<>();
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
sum.putIfAbsent(nums[i] + nums[j], new HashSet<>());
sum.get(nums[i] + nums[j]).add(new Pair(nums[i], nums[j], i, j));
}
}
HashSet<Pair> used = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (i != nums.length - 1 && nums[i] == nums[i + 1]) {
continue;
}
int n = nums[i];
if (sum.containsKey(-n)) {
HashSet<Pair> idxPair = sum.get(-n);
for (Pair p : idxPair) {
Pair dup_check = new Pair(Math.min(n, p.x), Math.max(n, p.y));
if (!p.conficts(i) && !used.contains(dup_check)) {
LinkedList<Integer> combination = new LinkedList<>();
combination.add(n);
combination.add(p.x);
combination.add(p.y);
result.add(combination);
used.add(dup_check);
}
}
}
}
return result;
}
} | LeetCode 15 Alternative
| LeetCode/15.3Sum.java | LeetCode 15 Alternative | <ide><path>eetCode/15.3Sum.java
<ide> public int hashCode() {
<ide> return x.hashCode() * 31 + y.hashCode();
<ide> }
<del>
<del> public String toString() {
<del> return x + " " + y + " " + idx1 + " " + idx2;
<del> }
<ide> }
<ide>
<ide> public class Solution {
<ide> List<List<Integer>> result = new LinkedList<>();
<ide> HashMap<Integer, HashSet<Pair>> sum = new HashMap<>();
<ide> for (int i = 0; i < nums.length - 1; i++) {
<add> if (i != 0 && nums[i - 1] == nums[i]) {
<add> continue;
<add> }
<ide> for (int j = i + 1; j < nums.length; j++) {
<add> if (j != i + 1 && nums[j - 1] == nums[j]) {
<add> continue;
<add> }
<ide> sum.putIfAbsent(nums[i] + nums[j], new HashSet<>());
<ide> sum.get(nums[i] + nums[j]).add(new Pair(nums[i], nums[j], i, j));
<ide> } |
|
Java | apache-2.0 | f34bd79b9a92f23c1fc5e185e074d7faa880fc0b | 0 | codefollower/Cassandra-Research,driftx/cassandra,scylladb/scylla-tools-java,GabrielNicolasAvellaneda/cassandra,bdeggleston/cassandra,iamaleksey/cassandra,LatencyUtils/cassandra-stress2,leomrocha/cassandra,tongjixianing/projects,DavidHerzogTU-Berlin/cassandra,phact/cassandra,joesiewert/cassandra,DICL/cassandra,michaelmior/cassandra,ben-manes/cassandra,AtwooTM/cassandra,fengshao0907/cassandra-1,aweisberg/cassandra,ollie314/cassandra,dprguiuc/Cassandra-Wasef,aureagle/cassandra,belliottsmith/cassandra,snazy/cassandra,jeromatron/cassandra,sayanh/ViewMaintenanceSupport,likaiwalkman/cassandra,rmarchei/cassandra,exoscale/cassandra,pcn/cassandra-1,emolsson/cassandra,rogerchina/cassandra,mashuai/Cassandra-Research,AtwooTM/cassandra,jbellis/cassandra,whitepages/cassandra,aweisberg/cassandra,knifewine/cassandra,asias/cassandra,pauloricardomg/cassandra,vaibhi9/cassandra,ifesdjeen/cassandra,GabrielNicolasAvellaneda/cassandra,mike-tr-adamson/cassandra,sivikt/cassandra,nakomis/cassandra,aarushi12002/cassandra,snazy/cassandra,weipinghe/cassandra,belliottsmith/cassandra,thelastpickle/cassandra,matthewtt/cassandra_read,adejanovski/cassandra,codefollower/Cassandra-Research,Imran-C/cassandra,lalithsuresh/cassandra-c3,cooldoger/cassandra,vramaswamy456/cassandra,christian-esken/cassandra,jrwest/cassandra,DICL/cassandra,likaiwalkman/cassandra,darach/cassandra,yonglehou/cassandra,jasonstack/cassandra,ejankan/cassandra,taigetco/cassandra_read,apache/cassandra,clohfink/cassandra,driftx/cassandra,pallavi510/cassandra,HidemotoNakada/cassandra-udf,pcmanus/cassandra,aboudreault/cassandra,modempachev4/kassandra,nitsanw/cassandra,bcoverston/apache-hosted-cassandra,guanxi55nba/db-improvement,kgreav/cassandra,pofallon/cassandra,chbatey/cassandra-1,emolsson/cassandra,jkni/cassandra,bmel/cassandra,boneill42/cassandra,stef1927/cassandra,swps/cassandra,qinjin/mdtc-cassandra,strapdata/cassandra,snazy/cassandra,scylladb/scylla-tools-java,jeffjirsa/cassandra,nitsanw/cassandra,jasobrown/cassandra,nutbunnies/cassandra,tongjixianing/projects,weideng1/cassandra,sharvanath/cassandra,kangkot/stratio-cassandra,phact/cassandra,thelastpickle/cassandra,nutbunnies/cassandra,LatencyUtils/cassandra-stress2,mike-tr-adamson/cassandra,wreda/cassandra,beobal/cassandra,pkdevbox/cassandra,Imran-C/cassandra,EnigmaCurry/cassandra,beobal/cassandra,ptuckey/cassandra,dprguiuc/Cassandra-Wasef,blerer/cassandra,ptnapoleon/cassandra,Instagram/cassandra,mkjellman/cassandra,jkni/cassandra,jrwest/cassandra,Instagram/cassandra,a-buck/cassandra,fengshao0907/Cassandra-Research,Jaumo/cassandra,guard163/cassandra,vaibhi9/cassandra,bcoverston/cassandra,mheffner/cassandra-1,DavidHerzogTU-Berlin/cassandraToRun,WorksApplications/cassandra,HidemotoNakada/cassandra-udf,sivikt/cassandra,macintoshio/cassandra,rdio/cassandra,sriki77/cassandra,dkua/cassandra,stef1927/cassandra,regispl/cassandra,jsanda/cassandra,lalithsuresh/cassandra-c3,apache/cassandra,mkjellman/cassandra,xiongzheng/Cassandra-Research,blambov/cassandra,darach/cassandra,whitepages/cassandra,bcoverston/apache-hosted-cassandra,josh-mckenzie/cassandra,rogerchina/cassandra,bdeggleston/cassandra,jasonstack/cassandra,JeremiahDJordan/cassandra,rmarchei/cassandra,yanbit/cassandra,yanbit/cassandra,mshuler/cassandra,emolsson/cassandra,fengshao0907/cassandra-1,aboudreault/cassandra,belliottsmith/cassandra,Jollyplum/cassandra,EnigmaCurry/cassandra,nvoron23/cassandra,rmarchei/cassandra,RyanMagnusson/cassandra,WorksApplications/cassandra,yonglehou/cassandra,pkdevbox/cassandra,yonglehou/cassandra,sayanh/ViewMaintenanceCassandra,blambov/cassandra,sayanh/ViewMaintenanceCassandra,leomrocha/cassandra,nakomis/cassandra,dongjiaqiang/cassandra,tjake/cassandra,rdio/cassandra,pthomaid/cassandra,thobbs/cassandra,tommystendahl/cassandra,iburmistrov/Cassandra,guard163/cassandra,rackerlabs/cloudmetrics-cassandra,ejankan/cassandra,krummas/cassandra,JeremiahDJordan/cassandra,pallavi510/cassandra,darach/cassandra,apache/cassandra,nlalevee/cassandra,MasahikoSawada/cassandra,christian-esken/cassandra,pcn/cassandra-1,sedulam/CASSANDRA-12201,josh-mckenzie/cassandra,driftx/cassandra,tjake/cassandra,modempachev4/kassandra,sayanh/ViewMaintenanceSupport,mike-tr-adamson/cassandra,mheffner/cassandra-1,kgreav/cassandra,mheffner/cassandra-1,shawnkumar/cstargraph,szhou1234/cassandra,guanxi55nba/db-improvement,hengxin/cassandra,driftx/cassandra,lalithsuresh/cassandra-c3,pcn/cassandra-1,Bj0rnen/cassandra,cooldoger/cassandra,jeffjirsa/cassandra,ifesdjeen/cassandra,szhou1234/cassandra,chaordic/cassandra,wreda/cassandra,scaledata/cassandra,Stratio/stratio-cassandra,tjake/cassandra,christian-esken/cassandra,Stratio/cassandra,vramaswamy456/cassandra,jrwest/cassandra,mkjellman/cassandra,tommystendahl/cassandra,sharvanath/cassandra,ollie314/cassandra,AtwooTM/cassandra,Jaumo/cassandra,bcoverston/cassandra,jbellis/cassandra,aboudreault/cassandra,Stratio/cassandra,mambocab/cassandra,qinjin/mdtc-cassandra,sriki77/cassandra,fengshao0907/cassandra-1,pthomaid/cassandra,vaibhi9/cassandra,qinjin/mdtc-cassandra,mike-tr-adamson/cassandra,mgmuscari/cassandra-cdh4,kgreav/cassandra,DICL/cassandra,project-zerus/cassandra,DavidHerzogTU-Berlin/cassandra,newrelic-forks/cassandra,jasonwee/cassandra,kangkot/stratio-cassandra,sluk3r/cassandra,mashuai/Cassandra-Research,vramaswamy456/cassandra,swps/cassandra,nakomis/cassandra,jsanda/cassandra,jeromatron/cassandra,nlalevee/cassandra,krummas/cassandra,Jollyplum/cassandra,WorksApplications/cassandra,mshuler/cassandra,jsanda/cassandra,kangkot/stratio-cassandra,beobal/cassandra,cooldoger/cassandra,dkua/cassandra,rackerlabs/cloudmetrics-cassandra,sbtourist/cassandra,RyanMagnusson/cassandra,helena/cassandra,michaelmior/cassandra,bcoverston/cassandra,ifesdjeen/cassandra,mgmuscari/cassandra-cdh4,mt0803/cassandra,aureagle/cassandra,miguel0afd/cassandra-cqlMod,adejanovski/cassandra,juiceblender/cassandra,guanxi55nba/db-improvement,ben-manes/cassandra,knifewine/cassandra,macintoshio/cassandra,tommystendahl/cassandra,spodkowinski/cassandra,sluk3r/cassandra,DavidHerzogTU-Berlin/cassandraToRun,iamaleksey/cassandra,yanbit/cassandra,heiko-braun/cassandra,cooldoger/cassandra,mshuler/cassandra,caidongyun/cassandra,blambov/cassandra,matthewtt/cassandra_read,pcmanus/cassandra,heiko-braun/cassandra,pofallon/cassandra,jeffjirsa/cassandra,xiongzheng/Cassandra-Research,mkjellman/cassandra,dongjiaqiang/cassandra,guard163/cassandra,chaordic/cassandra,josh-mckenzie/cassandra,yukim/cassandra,thobbs/cassandra,joesiewert/cassandra,codefollower/Cassandra-Research,yhnishi/cassandra,nitsanw/cassandra,clohfink/cassandra,Instagram/cassandra,knifewine/cassandra,stef1927/cassandra,gdusbabek/cassandra,adelapena/cassandra,snazy/cassandra,aweisberg/cassandra,yukim/cassandra,miguel0afd/cassandra-cqlMod,LatencyUtils/cassandra-stress2,bcoverston/apache-hosted-cassandra,clohfink/cassandra,adelapena/cassandra,exoscale/cassandra,weipinghe/cassandra,DikangGu/cassandra,DavidHerzogTU-Berlin/cassandraToRun,gdusbabek/cassandra,MasahikoSawada/cassandra,krummas/cassandra,HidemotoNakada/cassandra-udf,RyanMagnusson/cassandra,thelastpickle/cassandra,weideng1/cassandra,weipinghe/cassandra,jasonwee/cassandra,yangzhe1991/cassandra,swps/cassandra,dkua/cassandra,bmel/cassandra,regispl/cassandra,michaelmior/cassandra,pallavi510/cassandra,juiceblender/cassandra,Bj0rnen/cassandra,szhou1234/cassandra,taigetco/cassandra_read,ifesdjeen/cassandra,ptnapoleon/cassandra,sriki77/cassandra,scylladb/scylla-tools-java,kangkot/stratio-cassandra,bpupadhyaya/cassandra,chaordic/cassandra,joesiewert/cassandra,exoscale/cassandra,hhorii/cassandra,adelapena/cassandra,DikangGu/cassandra,ejankan/cassandra,dongjiaqiang/cassandra,caidongyun/cassandra,Instagram/cassandra,blerer/cassandra,macintoshio/cassandra,pthomaid/cassandra,pauloricardomg/cassandra,bmel/cassandra,boneill42/cassandra,carlyeks/cassandra,gdusbabek/cassandra,strapdata/cassandra,aarushi12002/cassandra,thobbs/cassandra,shawnkumar/cstargraph,likaiwalkman/cassandra,asias/cassandra,spodkowinski/cassandra,clohfink/cassandra,mambocab/cassandra,sedulam/CASSANDRA-12201,instaclustr/cassandra,michaelsembwever/cassandra,krummas/cassandra,mambocab/cassandra,Stratio/stratio-cassandra,fengshao0907/Cassandra-Research,beobal/cassandra,ibmsoe/cassandra,mashuai/Cassandra-Research,Imran-C/cassandra,adejanovski/cassandra,instaclustr/cassandra,WorksApplications/cassandra,thelastpickle/cassandra,EnigmaCurry/cassandra,yangzhe1991/cassandra,newrelic-forks/cassandra,rackerlabs/cloudmetrics-cassandra,spodkowinski/cassandra,project-zerus/cassandra,mgmuscari/cassandra-cdh4,weideng1/cassandra,aweisberg/cassandra,nvoron23/cassandra,shawnkumar/cstargraph,rdio/cassandra,blerer/cassandra,asias/cassandra,sayanh/ViewMaintenanceCassandra,jasonstack/cassandra,blambov/cassandra,nutbunnies/cassandra,instaclustr/cassandra,pcmanus/cassandra,Stratio/stratio-cassandra,kangkot/stratio-cassandra,xiongzheng/Cassandra-Research,pauloricardomg/cassandra,adelapena/cassandra,hengxin/cassandra,guanxi55nba/key-value-store,yhnishi/cassandra,chbatey/cassandra-1,Bj0rnen/cassandra,dprguiuc/Cassandra-Wasef,jasonwee/cassandra,ollie314/cassandra,michaelsembwever/cassandra,nlalevee/cassandra,DikangGu/cassandra,ptnapoleon/cassandra,aarushi12002/cassandra,mt0803/cassandra,wreda/cassandra,taigetco/cassandra_read,guanxi55nba/key-value-store,pauloricardomg/cassandra,Stratio/cassandra,mt0803/cassandra,michaelsembwever/cassandra,sedulam/CASSANDRA-12201,matthewtt/cassandra_read,kgreav/cassandra,Stratio/stratio-cassandra,caidongyun/cassandra,jeromatron/cassandra,stef1927/cassandra,ibmsoe/cassandra,ptuckey/cassandra,strapdata/cassandra,scaledata/cassandra,regispl/cassandra,tongjixianing/projects,Jaumo/cassandra,whitepages/cassandra,bdeggleston/cassandra,yangzhe1991/cassandra,helena/cassandra,hhorii/cassandra,sharvanath/cassandra,heiko-braun/cassandra,yukim/cassandra,jrwest/cassandra,Jollyplum/cassandra,szhou1234/cassandra,strapdata/cassandra,scaledata/cassandra,DavidHerzogTU-Berlin/cassandra,sluk3r/cassandra,chbatey/cassandra-1,jbellis/cassandra,ben-manes/cassandra,hhorii/cassandra,leomrocha/cassandra,jkni/cassandra,iburmistrov/Cassandra,mshuler/cassandra,tjake/cassandra,juiceblender/cassandra,ptuckey/cassandra,juiceblender/cassandra,sbtourist/cassandra,sbtourist/cassandra,fengshao0907/Cassandra-Research,pkdevbox/cassandra,spodkowinski/cassandra,pofallon/cassandra,jasobrown/cassandra,aureagle/cassandra,yukim/cassandra,a-buck/cassandra,modempachev4/kassandra,bpupadhyaya/cassandra,josh-mckenzie/cassandra,miguel0afd/cassandra-cqlMod,jasobrown/cassandra,boneill42/cassandra,tommystendahl/cassandra,scylladb/scylla-tools-java,jeffjirsa/cassandra,ibmsoe/cassandra,project-zerus/cassandra,iamaleksey/cassandra,iburmistrov/Cassandra,michaelsembwever/cassandra,carlyeks/cassandra,apache/cassandra,yhnishi/cassandra,blerer/cassandra,iamaleksey/cassandra,phact/cassandra,hengxin/cassandra,instaclustr/cassandra,nvoron23/cassandra,jasobrown/cassandra,guanxi55nba/key-value-store,rogerchina/cassandra,bdeggleston/cassandra,carlyeks/cassandra,sivikt/cassandra,bcoverston/cassandra,JeremiahDJordan/cassandra,belliottsmith/cassandra,a-buck/cassandra,MasahikoSawada/cassandra,newrelic-forks/cassandra,Stratio/stratio-cassandra,helena/cassandra,GabrielNicolasAvellaneda/cassandra,bpupadhyaya/cassandra | package org.apache.cassandra.db.compaction;
/*
*
* 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.
*
*/
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.util.*;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.dht.Bounds;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.sstable.SSTable;
import org.apache.cassandra.io.sstable.SSTableReader;
import org.apache.cassandra.io.util.FileUtils;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import static org.apache.cassandra.db.compaction.AbstractCompactionStrategy.filterSuspectSSTables;
public class LeveledManifest
{
private static final Logger logger = LoggerFactory.getLogger(LeveledManifest.class);
public static final String EXTENSION = ".json";
/**
* limit the number of L0 sstables we do at once, because compaction bloom filter creation
* uses a pessimistic estimate of how many keys overlap (none), so we risk wasting memory
* or even OOMing when compacting highly overlapping sstables
*/
private static final int MAX_COMPACTING_L0 = 32;
private final ColumnFamilyStore cfs;
private final List<SSTableReader>[] generations;
private final Map<SSTableReader, Integer> sstableGenerations;
private final RowPosition[] lastCompactedKeys;
private final int maxSSTableSizeInBytes;
private LeveledManifest(ColumnFamilyStore cfs, int maxSSTableSizeInMB)
{
this.cfs = cfs;
this.maxSSTableSizeInBytes = maxSSTableSizeInMB * 1024 * 1024;
// allocate enough generations for a PB of data
int n = (int) Math.log10(1000 * 1000 * 1000 / maxSSTableSizeInMB);
generations = new List[n];
lastCompactedKeys = new RowPosition[n];
for (int i = 0; i < generations.length; i++)
{
generations[i] = new ArrayList<SSTableReader>();
lastCompactedKeys[i] = cfs.partitioner.getMinimumToken().minKeyBound();
}
sstableGenerations = new HashMap<SSTableReader, Integer>();
}
static LeveledManifest create(ColumnFamilyStore cfs, int maxSSTableSize)
{
return create(cfs, maxSSTableSize, cfs.getSSTables());
}
public static LeveledManifest create(ColumnFamilyStore cfs, int maxSSTableSize, Iterable<SSTableReader> sstables)
{
LeveledManifest manifest = new LeveledManifest(cfs, maxSSTableSize);
load(cfs, manifest, sstables);
// ensure all SSTables are in the manifest
for (SSTableReader ssTableReader : sstables)
{
if (manifest.levelOf(ssTableReader) < 0)
manifest.add(ssTableReader);
}
return manifest;
}
private static void load(ColumnFamilyStore cfs, LeveledManifest manifest, Iterable<SSTableReader> sstables)
{
File manifestFile = tryGetManifest(cfs);
if (manifestFile == null)
return;
ObjectMapper m = new ObjectMapper();
try
{
JsonNode rootNode = m.readValue(manifestFile, JsonNode.class);
JsonNode generations = rootNode.get("generations");
assert generations.isArray();
for (JsonNode generation : generations)
{
int level = generation.get("generation").getIntValue();
JsonNode generationValues = generation.get("members");
for (JsonNode generationValue : generationValues)
{
for (SSTableReader ssTableReader : sstables)
{
if (ssTableReader.descriptor.generation == generationValue.getIntValue())
{
logger.debug("Loading {} at L{}", ssTableReader, level);
manifest.add(ssTableReader, level);
}
}
}
}
}
catch (Exception e)
{
// TODO try to recover -old first
logger.error("Manifest present but corrupt. Cassandra will compact levels from scratch", e);
}
}
public synchronized void add(SSTableReader reader)
{
logDistribution();
logger.debug("Adding {} to L0", reader);
add(reader, 0);
serialize();
}
/**
* if the number of SSTables in the current compacted set *by itself* exceeds the target level's
* (regardless of the level's current contents), find an empty level instead
*/
private int skipLevels(int newLevel, Iterable<SSTableReader> added)
{
while (maxBytesForLevel(newLevel) < SSTableReader.getTotalBytes(added)
&& generations[(newLevel + 1)].isEmpty())
{
newLevel++;
}
return newLevel;
}
public synchronized void promote(Iterable<SSTableReader> removed, Iterable<SSTableReader> added)
{
assert !Iterables.isEmpty(removed); // use add() instead of promote when adding new sstables
logDistribution();
if (logger.isDebugEnabled())
logger.debug("Replacing [" + toString(removed) + "]");
// the level for the added sstables is the max of the removed ones,
// plus one if the removed were all on the same level
int minimumLevel = Integer.MAX_VALUE;
int maximumLevel = 0;
for (SSTableReader sstable : removed)
{
int thisLevel = remove(sstable);
assert thisLevel >= 0;
maximumLevel = Math.max(maximumLevel, thisLevel);
minimumLevel = Math.min(minimumLevel, thisLevel);
}
// it's valid to do a remove w/o an add (e.g. on truncate)
if (!added.iterator().hasNext())
return;
int newLevel;
if (minimumLevel == 0 && maximumLevel == 0 && SSTable.getTotalBytes(removed) <= maxSSTableSizeInBytes)
{
// special case for tiny L0 sstables; see CASSANDRA-4341
newLevel = 0;
}
else
{
newLevel = minimumLevel == maximumLevel ? maximumLevel + 1 : maximumLevel;
newLevel = skipLevels(newLevel, added);
assert newLevel > 0;
}
if (logger.isDebugEnabled())
logger.debug("Adding [{}] at L{}", toString(added), newLevel);
lastCompactedKeys[minimumLevel] = SSTable.sstableOrdering.max(added).last;
for (SSTableReader ssTableReader : added)
add(ssTableReader, newLevel);
// Fix overlapping sstables from CASSANDRA-4321/4411
if (newLevel != 0)
repairOverlappingSSTables(newLevel);
serialize();
}
public synchronized void repairOverlappingSSTables(int level)
{
SSTableReader previous = null;
Collections.sort(generations[level], SSTable.sstableComparator);
List<SSTableReader> outOfOrderSSTables = new ArrayList<SSTableReader>();
for (SSTableReader current : generations[level])
{
if (previous != null && current.first.compareTo(previous.last) <= 0)
{
logger.error(String.format("At level %d, %s [%s, %s] overlaps %s [%s, %s]. This is caused by a bug in Cassandra 1.1.0 .. 1.1.3. Sending back to L0. If you have not yet run scrub, you should do so since you may also have rows out-of-order within an sstable",
level, previous, previous.first, previous.last, current, current.first, current.last));
outOfOrderSSTables.add(current);
}
else
{
previous = current;
}
}
if (!outOfOrderSSTables.isEmpty())
{
for (SSTableReader sstable : outOfOrderSSTables)
sendBackToL0(sstable);
serialize();
}
}
public synchronized void replace(Iterable<SSTableReader> removed, Iterable<SSTableReader> added)
{
// replace is for compaction operation that operate on exactly one sstable, with no merging.
// Thus, removed will be exactly one sstable, and added will be 0 or 1.
assert Iterables.size(removed) == 1 : Iterables.size(removed);
assert Iterables.size(added) <= 1 : Iterables.size(added);
logDistribution();
logger.debug("Replacing {} with {}", removed, added);
int level = remove(removed.iterator().next());
if (!Iterables.isEmpty(added))
add(added.iterator().next(), level);
serialize();
}
private synchronized void sendBackToL0(SSTableReader sstable)
{
remove(sstable);
add(sstable, 0);
}
private String toString(Iterable<SSTableReader> sstables)
{
StringBuilder builder = new StringBuilder();
for (SSTableReader sstable : sstables)
{
builder.append(sstable.descriptor.cfname)
.append('-')
.append(sstable.descriptor.generation)
.append("(L")
.append(levelOf(sstable))
.append("), ");
}
return builder.toString();
}
private long maxBytesForLevel(int level)
{
if (level == 0)
return 4L * maxSSTableSizeInBytes;
double bytes = Math.pow(10, level) * maxSSTableSizeInBytes;
if (bytes > Long.MAX_VALUE)
throw new RuntimeException("At most " + Long.MAX_VALUE + " bytes may be in a compaction level; your maxSSTableSize must be absurdly high to compute " + bytes);
return (long) bytes;
}
public synchronized Collection<SSTableReader> getCompactionCandidates()
{
// LevelDB gives each level a score of how much data it contains vs its ideal amount, and
// compacts the level with the highest score. But this falls apart spectacularly once you
// get behind. Consider this set of levels:
// L0: 988 [ideal: 4]
// L1: 117 [ideal: 10]
// L2: 12 [ideal: 100]
//
// The problem is that L0 has a much higher score (almost 250) than L1 (11), so what we'll
// do is compact a batch of MAX_COMPACTING_L0 sstables with all 117 L1 sstables, and put the
// result (say, 120 sstables) in L1. Then we'll compact the next batch of MAX_COMPACTING_L0,
// and so forth. So we spend most of our i/o rewriting the L1 data with each batch.
//
// If we could just do *all* L0 a single time with L1, that would be ideal. But we can't
// -- see the javadoc for MAX_COMPACTING_L0.
//
// LevelDB's way around this is to simply block writes if L0 compaction falls behind.
// We don't have that luxury.
//
// So instead, we force compacting higher levels first. This may not minimize the number
// of reads done as quickly in the short term, but it minimizes the i/o needed to compact
// optimially which gives us a long term win.
for (int i = generations.length - 1; i >= 0; i--)
{
List<SSTableReader> sstables = generations[i];
if (sstables.isEmpty())
continue; // mostly this just avoids polluting the debug log with zero scores
double score = (double)SSTableReader.getTotalBytes(sstables) / (double)maxBytesForLevel(i);
logger.debug("Compaction score for level {} is {}", i, score);
// L0 gets a special case that if we don't have anything more important to do,
// we'll go ahead and compact if we have more than one sstable
if (score > 1.001 || (i == 0 && sstables.size() > 1))
{
Collection<SSTableReader> candidates = getCandidatesFor(i);
if (logger.isDebugEnabled())
logger.debug("Compaction candidates for L{} are {}", i, toString(candidates));
if (!candidates.isEmpty())
return candidates;
}
}
return Collections.emptyList();
}
public int getLevelSize(int i)
{
return generations.length > i ? generations[i].size() : 0;
}
private void logDistribution()
{
if (logger.isDebugEnabled())
{
for (int i = 0; i < generations.length; i++)
{
if (!generations[i].isEmpty())
{
logger.debug("L{} contains {} SSTables ({} bytes) in {}",
new Object[] {i, generations[i].size(), SSTableReader.getTotalBytes(generations[i]), this});
}
}
}
}
int levelOf(SSTableReader sstable)
{
Integer level = sstableGenerations.get(sstable);
if (level == null)
return -1;
return level.intValue();
}
private int remove(SSTableReader reader)
{
int level = levelOf(reader);
assert level >= 0 : reader + " not present in manifest";
generations[level].remove(reader);
sstableGenerations.remove(reader);
return level;
}
private void add(SSTableReader sstable, int level)
{
assert level < generations.length : "Invalid level " + level + " out of " + (generations.length - 1);
generations[level].add(sstable);
sstableGenerations.put(sstable, Integer.valueOf(level));
}
private static Set<SSTableReader> overlapping(Collection<SSTableReader> candidates, Iterable<SSTableReader> others)
{
assert !candidates.isEmpty();
/*
* Picking each sstable from others that overlap one of the sstable of candidates is not enough
* because you could have the following situation:
* candidates = [ s1(a, c), s2(m, z) ]
* others = [ s3(e, g) ]
* In that case, s2 overlaps none of s1 or s2, but if we compact s1 with s2, the resulting sstable will
* overlap s3, so we must return s3.
*
* Thus, the correct approach is to pick sstables overlapping anything between the first key in all
* the candidate sstables, and the last.
*/
Iterator<SSTableReader> iter = candidates.iterator();
SSTableReader sstable = iter.next();
Token first = sstable.first.token;
Token last = sstable.last.token;
while (iter.hasNext())
{
sstable = iter.next();
first = first.compareTo(sstable.first.token) <= 0 ? first : sstable.first.token;
last = last.compareTo(sstable.last.token) >= 0 ? last : sstable.last.token;
}
return overlapping(first, last, others);
}
private static Set<SSTableReader> overlapping(SSTableReader sstable, Iterable<SSTableReader> others)
{
return overlapping(sstable.first.token, sstable.last.token, others);
}
/**
* @return sstables from @param sstables that contain keys between @param start and @param end, inclusive.
*/
private static Set<SSTableReader> overlapping(Token start, Token end, Iterable<SSTableReader> sstables)
{
assert start.compareTo(end) <= 0;
Set<SSTableReader> overlapped = new HashSet<SSTableReader>();
Bounds<Token> promotedBounds = new Bounds<Token>(start, end);
for (SSTableReader candidate : sstables)
{
Bounds<Token> candidateBounds = new Bounds<Token>(candidate.first.token, candidate.last.token);
if (candidateBounds.intersects(promotedBounds))
overlapped.add(candidate);
}
return overlapped;
}
private Collection<SSTableReader> getCandidatesFor(int level)
{
assert !generations[level].isEmpty();
logger.debug("Choosing candidates for L{}", level);
if (level == 0)
{
// L0 is the dumping ground for new sstables which thus may overlap each other.
//
// We treat L0 compactions specially:
// 1a. add sstables to the candidate set until we have at least maxSSTableSizeInMB
// 1b. prefer choosing older sstables as candidates, to newer ones
// 1c. any L0 sstables that overlap a candidate, will also become candidates
// 2. At most MAX_COMPACTING_L0 sstables from L0 will be compacted at once
// 3. If total candidate size is less than maxSSTableSizeInMB, we won't bother compacting with L1,
// and the result of the compaction will stay in L0 instead of being promoted (see promote())
//
// Note that we ignore suspect-ness of L1 sstables here, since if an L1 sstable is suspect we're
// basically screwed, since we expect all or most L0 sstables to overlap with each L1 sstable.
// So if an L1 sstable is suspect we can't do much besides try anyway and hope for the best.
Set<SSTableReader> candidates = new HashSet<SSTableReader>();
Set<SSTableReader> remaining = new HashSet<SSTableReader>(generations[0]);
List<SSTableReader> ageSortedSSTables = new ArrayList<SSTableReader>(generations[0]);
Collections.sort(ageSortedSSTables, SSTable.maxTimestampComparator);
for (SSTableReader sstable : ageSortedSSTables)
{
if (candidates.contains(sstable))
continue;
for (SSTableReader newCandidate : Sets.union(Collections.singleton(sstable), overlapping(sstable, remaining)))
{
if (!newCandidate.isMarkedSuspect())
{
candidates.add(newCandidate);
remaining.remove(newCandidate);
}
}
if (candidates.size() > MAX_COMPACTING_L0)
{
// limit to only the MAX_COMPACTING_L0 oldest candidates
List<SSTableReader> ageSortedCandidates = new ArrayList<SSTableReader>(candidates);
Collections.sort(ageSortedCandidates, SSTable.maxTimestampComparator);
candidates = new HashSet<SSTableReader>(ageSortedCandidates.subList(0, MAX_COMPACTING_L0));
break;
}
}
if (SSTable.getTotalBytes(candidates) > maxSSTableSizeInBytes)
{
// add sstables from L1 that overlap candidates
candidates.addAll(overlapping(candidates, generations[1]));
}
return candidates.size() > 1 ? candidates : Collections.<SSTableReader>emptyList();
}
// for non-L0 compactions, pick up where we left off last time
Collections.sort(generations[level], SSTable.sstableComparator);
int start = 0; // handles case where the prior compaction touched the very last range
for (int i = 0; i < generations[level].size(); i++)
{
SSTableReader sstable = generations[level].get(i);
if (sstable.first.compareTo(lastCompactedKeys[level]) > 0)
{
start = i;
break;
}
}
// look for a non-suspect table to compact with, starting with where we left off last time,
// and wrapping back to the beginning of the generation if necessary
int i = start;
outer:
while (true)
{
SSTableReader sstable = generations[level].get(i);
Set<SSTableReader> candidates = Sets.union(Collections.singleton(sstable), overlapping(sstable, generations[(level + 1)]));
for (SSTableReader candidate : candidates)
{
if (candidate.isMarkedSuspect())
{
i = (i + 1) % generations[level].size();
if (i == start)
break outer;
continue outer;
}
}
return candidates;
}
// all the sstables were suspect or overlapped with something suspect
return Collections.emptyList();
}
public static File tryGetManifest(ColumnFamilyStore cfs)
{
return cfs.directories.tryGetLeveledManifest();
}
public synchronized void serialize()
{
File manifestFile = cfs.directories.getOrCreateLeveledManifest();
File oldFile = new File(manifestFile.getPath().replace(EXTENSION, "-old.json"));
File tmpFile = new File(manifestFile.getPath().replace(EXTENSION, "-tmp.json"));
JsonFactory f = new JsonFactory();
try
{
JsonGenerator g = f.createJsonGenerator(tmpFile, JsonEncoding.UTF8);
g.useDefaultPrettyPrinter();
g.writeStartObject();
g.writeArrayFieldStart("generations");
for (int level = 0; level < generations.length; level++)
{
g.writeStartObject();
g.writeNumberField("generation", level);
g.writeArrayFieldStart("members");
for (SSTableReader ssTableReader : generations[level])
g.writeNumber(ssTableReader.descriptor.generation);
g.writeEndArray(); // members
g.writeEndObject(); // generation
}
g.writeEndArray(); // for field generations
g.writeEndObject(); // write global object
g.close();
if (oldFile.exists() && manifestFile.exists())
FileUtils.deleteWithConfirm(oldFile);
if (manifestFile.exists())
FileUtils.renameWithConfirm(manifestFile, oldFile);
assert tmpFile.exists();
FileUtils.renameWithConfirm(tmpFile, manifestFile);
logger.debug("Saved manifest {}", manifestFile);
}
catch (IOException e)
{
throw new IOError(e);
}
}
@Override
public String toString()
{
return "Manifest@" + hashCode();
}
public int getLevelCount()
{
for (int i = generations.length - 1; i >= 0; i--)
{
if (generations[i].size() > 0)
return i;
}
return 0;
}
public List<SSTableReader> getLevel(int i)
{
return generations[i];
}
public synchronized int getEstimatedTasks()
{
long tasks = 0;
long[] estimated = new long[generations.length];
for (int i = generations.length - 1; i >= 0; i--)
{
List<SSTableReader> sstables = generations[i];
estimated[i] = Math.max(0L, SSTableReader.getTotalBytes(sstables) - maxBytesForLevel(i)) / maxSSTableSizeInBytes;
tasks += estimated[i];
}
logger.debug("Estimating {} compactions to do for {}.{}",
new Object[] {Arrays.toString(estimated), cfs.table.name, cfs.columnFamily});
return Ints.checkedCast(tasks);
}
}
| src/java/org/apache/cassandra/db/compaction/LeveledManifest.java | package org.apache.cassandra.db.compaction;
/*
*
* 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.
*
*/
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.util.*;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.dht.Bounds;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.sstable.SSTable;
import org.apache.cassandra.io.sstable.SSTableReader;
import org.apache.cassandra.io.util.FileUtils;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import static org.apache.cassandra.db.compaction.AbstractCompactionStrategy.filterSuspectSSTables;
public class LeveledManifest
{
private static final Logger logger = LoggerFactory.getLogger(LeveledManifest.class);
public static final String EXTENSION = ".json";
/**
* limit the number of L0 sstables we do at once, because compaction bloom filter creation
* uses a pessimistic estimate of how many keys overlap (none), so we risk wasting memory
* or even OOMing when compacting highly overlapping sstables
*/
private static final int MAX_COMPACTING_L0 = 32;
private final ColumnFamilyStore cfs;
private final List<SSTableReader>[] generations;
private final Map<SSTableReader, Integer> sstableGenerations;
private final RowPosition[] lastCompactedKeys;
private final int maxSSTableSizeInBytes;
private LeveledManifest(ColumnFamilyStore cfs, int maxSSTableSizeInMB)
{
this.cfs = cfs;
this.maxSSTableSizeInBytes = maxSSTableSizeInMB * 1024 * 1024;
// allocate enough generations for a PB of data
int n = (int) Math.log10(1000 * 1000 * 1000 / maxSSTableSizeInMB);
generations = new List[n];
lastCompactedKeys = new RowPosition[n];
for (int i = 0; i < generations.length; i++)
{
generations[i] = new ArrayList<SSTableReader>();
lastCompactedKeys[i] = cfs.partitioner.getMinimumToken().minKeyBound();
}
sstableGenerations = new HashMap<SSTableReader, Integer>();
}
static LeveledManifest create(ColumnFamilyStore cfs, int maxSSTableSize)
{
return create(cfs, maxSSTableSize, cfs.getSSTables());
}
public static LeveledManifest create(ColumnFamilyStore cfs, int maxSSTableSize, Iterable<SSTableReader> sstables)
{
LeveledManifest manifest = new LeveledManifest(cfs, maxSSTableSize);
load(cfs, manifest, sstables);
// ensure all SSTables are in the manifest
for (SSTableReader ssTableReader : sstables)
{
if (manifest.levelOf(ssTableReader) < 0)
manifest.add(ssTableReader);
}
return manifest;
}
private static void load(ColumnFamilyStore cfs, LeveledManifest manifest, Iterable<SSTableReader> sstables)
{
File manifestFile = tryGetManifest(cfs);
if (manifestFile == null)
return;
ObjectMapper m = new ObjectMapper();
try
{
JsonNode rootNode = m.readValue(manifestFile, JsonNode.class);
JsonNode generations = rootNode.get("generations");
assert generations.isArray();
for (JsonNode generation : generations)
{
int level = generation.get("generation").getIntValue();
JsonNode generationValues = generation.get("members");
for (JsonNode generationValue : generationValues)
{
for (SSTableReader ssTableReader : sstables)
{
if (ssTableReader.descriptor.generation == generationValue.getIntValue())
{
logger.debug("Loading {} at L{}", ssTableReader, level);
manifest.add(ssTableReader, level);
}
}
}
}
}
catch (Exception e)
{
// TODO try to recover -old first
logger.error("Manifest present but corrupt. Cassandra will compact levels from scratch", e);
}
}
public synchronized void add(SSTableReader reader)
{
logDistribution();
logger.debug("Adding {} to L0", reader);
add(reader, 0);
serialize();
}
/**
* if the number of SSTables in the current compacted set *by itself* exceeds the target level's
* (regardless of the level's current contents), find an empty level instead
*/
private int skipLevels(int newLevel, Iterable<SSTableReader> added)
{
while (maxBytesForLevel(newLevel) < SSTableReader.getTotalBytes(added)
&& generations[(newLevel + 1)].isEmpty())
{
newLevel++;
}
return newLevel;
}
public synchronized void promote(Iterable<SSTableReader> removed, Iterable<SSTableReader> added)
{
assert !Iterables.isEmpty(removed); // use add() instead of promote when adding new sstables
logDistribution();
if (logger.isDebugEnabled())
logger.debug("Replacing [" + toString(removed) + "]");
// the level for the added sstables is the max of the removed ones,
// plus one if the removed were all on the same level
int minimumLevel = Integer.MAX_VALUE;
int maximumLevel = 0;
for (SSTableReader sstable : removed)
{
int thisLevel = remove(sstable);
assert thisLevel >= 0;
maximumLevel = Math.max(maximumLevel, thisLevel);
minimumLevel = Math.min(minimumLevel, thisLevel);
}
// it's valid to do a remove w/o an add (e.g. on truncate)
if (!added.iterator().hasNext())
return;
int newLevel;
if (minimumLevel == 0 && maximumLevel == 0 && SSTable.getTotalBytes(removed) <= maxSSTableSizeInBytes)
{
// special case for tiny L0 sstables; see CASSANDRA-4341
newLevel = 0;
}
else
{
newLevel = minimumLevel == maximumLevel ? maximumLevel + 1 : maximumLevel;
newLevel = skipLevels(newLevel, added);
assert newLevel > 0;
}
if (logger.isDebugEnabled())
logger.debug("Adding [{}] at L{}", toString(added), newLevel);
lastCompactedKeys[minimumLevel] = SSTable.sstableOrdering.max(added).last;
for (SSTableReader ssTableReader : added)
add(ssTableReader, newLevel);
// Fix overlapping sstables from CASSANDRA-4321/4411
if (newLevel != 0)
repairOverlappingSSTables(newLevel);
serialize();
}
public synchronized void repairOverlappingSSTables(int level)
{
SSTableReader previous = null;
Collections.sort(generations[level], SSTable.sstableComparator);
List<SSTableReader> outOfOrderSSTables = new ArrayList<SSTableReader>();
for (SSTableReader current : generations[level])
{
if (previous != null && current.first.compareTo(previous.last) <= 0)
{
logger.error(String.format("At level %d, %s [%s, %s] overlaps %s [%s, %s]. This is caused by a bug in Cassandra 1.1.0 .. 1.1.3. Sending back to L0. If you have not yet run scrub, you should do so since you may also have rows out-of-order within an sstable",
level, previous, previous.first, previous.last, current, current.first, current.last));
outOfOrderSSTables.add(current);
}
else
{
previous = current;
}
}
if (!outOfOrderSSTables.isEmpty())
{
for (SSTableReader sstable : outOfOrderSSTables)
sendBackToL0(sstable);
serialize();
}
}
public synchronized void replace(Iterable<SSTableReader> removed, Iterable<SSTableReader> added)
{
// replace is for compaction operation that operate on exactly one sstable, with no merging.
// Thus, removed will be exactly one sstable, and added will be 0 or 1.
assert Iterables.size(removed) == 1 : Iterables.size(removed);
assert Iterables.size(added) <= 1 : Iterables.size(added);
logDistribution();
logger.debug("Replacing {} with {}", removed, added);
int level = remove(removed.iterator().next());
if (!Iterables.isEmpty(added))
add(added.iterator().next(), level);
serialize();
}
private synchronized void sendBackToL0(SSTableReader sstable)
{
remove(sstable);
add(sstable, 0);
}
private String toString(Iterable<SSTableReader> sstables)
{
StringBuilder builder = new StringBuilder();
for (SSTableReader sstable : sstables)
{
builder.append(sstable.descriptor.cfname)
.append('-')
.append(sstable.descriptor.generation)
.append("(L")
.append(levelOf(sstable))
.append("), ");
}
return builder.toString();
}
private long maxBytesForLevel(int level)
{
if (level == 0)
return 4L * maxSSTableSizeInBytes;
double bytes = Math.pow(10, level) * maxSSTableSizeInBytes;
if (bytes > Long.MAX_VALUE)
throw new RuntimeException("At most " + Long.MAX_VALUE + " bytes may be in a compaction level; your maxSSTableSize must be absurdly high to compute " + bytes);
return (long) bytes;
}
public synchronized Collection<SSTableReader> getCompactionCandidates()
{
// LevelDB gives each level a score of how much data it contains vs its ideal amount, and
// compacts the level with the highest score. But this falls apart spectacularly once you
// get behind. Consider this set of levels:
// L0: 988 [ideal: 4]
// L1: 117 [ideal: 10]
// L2: 12 [ideal: 100]
//
// The problem is that L0 has a much higher score (almost 250) than L1 (11), so what we'll
// do is compact a batch of MAX_COMPACTING_L0 sstables with all 117 L1 sstables, and put the
// result (say, 120 sstables) in L1. Then we'll compact the next batch of MAX_COMPACTING_L0,
// and so forth. So we spend most of our i/o rewriting the L1 data with each batch.
//
// If we could just do *all* L0 a single time with L1, that would be ideal. But we can't
// -- see the javadoc for MAX_COMPACTING_L0.
//
// LevelDB's way around this is to simply block writes if L0 compaction falls behind.
// We don't have that luxury.
//
// So instead, we force compacting higher levels first. This may not minimize the number
// of reads done as quickly in the short term, but it minimizes the i/o needed to compact
// optimially which gives us a long term win.
for (int i = generations.length - 1; i >= 0; i--)
{
List<SSTableReader> sstables = generations[i];
if (sstables.isEmpty())
continue; // mostly this just avoids polluting the debug log with zero scores
double score = (double)SSTableReader.getTotalBytes(sstables) / (double)maxBytesForLevel(i);
logger.debug("Compaction score for level {} is {}", i, score);
// L0 gets a special case that if we don't have anything more important to do,
// we'll go ahead and compact if we have more than one sstable
if (score > 1.001 || (i == 0 && sstables.size() > 1))
{
Collection<SSTableReader> candidates = getCandidatesFor(i);
if (logger.isDebugEnabled())
logger.debug("Compaction candidates for L{} are {}", i, toString(candidates));
if (!candidates.isEmpty())
return candidates;
}
}
return Collections.emptyList();
}
public int getLevelSize(int i)
{
return generations.length > i ? generations[i].size() : 0;
}
private void logDistribution()
{
if (logger.isDebugEnabled())
{
for (int i = 0; i < generations.length; i++)
{
if (!generations[i].isEmpty())
{
logger.debug("L{} contains {} SSTables ({} bytes) in {}",
new Object[] {i, generations[i].size(), SSTableReader.getTotalBytes(generations[i]), this});
}
}
}
}
int levelOf(SSTableReader sstable)
{
Integer level = sstableGenerations.get(sstable);
if (level == null)
return -1;
return level.intValue();
}
private int remove(SSTableReader reader)
{
int level = levelOf(reader);
assert level >= 0 : reader + " not present in manifest";
generations[level].remove(reader);
sstableGenerations.remove(reader);
return level;
}
private void add(SSTableReader sstable, int level)
{
assert level < generations.length : "Invalid level " + level + " out of " + (generations.length - 1);
generations[level].add(sstable);
sstableGenerations.put(sstable, Integer.valueOf(level));
}
private static Set<SSTableReader> overlapping(Collection<SSTableReader> candidates, Iterable<SSTableReader> others)
{
assert !candidates.isEmpty();
/*
* Picking each sstable from others that overlap one of the sstable of candidates is not enough
* because you could have the following situation:
* candidates = [ s1(a, c), s2(m, z) ]
* others = [ s3(e, g) ]
* In that case, s2 overlaps none of s1 or s2, but if we compact s1 with s2, the resulting sstable will
* overlap s3, so we must return s3.
*
* Thus, the correct approach is to pick sstables overlapping anything between the first key in all
* the candidate sstables, and the last.
*/
Iterator<SSTableReader> iter = candidates.iterator();
SSTableReader sstable = iter.next();
Token first = sstable.first.token;
Token last = sstable.last.token;
while (iter.hasNext())
{
sstable = iter.next();
first = first.compareTo(sstable.first.token) <= 0 ? first : sstable.first.token;
last = last.compareTo(sstable.last.token) >= 0 ? last : sstable.last.token;
}
return overlapping(first, last, others);
}
private static Set<SSTableReader> overlapping(SSTableReader sstable, Iterable<SSTableReader> others)
{
return overlapping(sstable.first.token, sstable.last.token, others);
}
/**
* @return sstables from @param sstables that contain keys between @param start and @param end, inclusive.
*/
private static Set<SSTableReader> overlapping(Token start, Token end, Iterable<SSTableReader> sstables)
{
assert start.compareTo(end) <= 0;
Set<SSTableReader> overlapped = new HashSet<SSTableReader>();
Bounds<Token> promotedBounds = new Bounds<Token>(start, end);
for (SSTableReader candidate : sstables)
{
Bounds<Token> candidateBounds = new Bounds<Token>(candidate.first.token, candidate.last.token);
if (candidateBounds.intersects(promotedBounds))
overlapped.add(candidate);
}
return overlapped;
}
private Collection<SSTableReader> getCandidatesFor(int level)
{
assert !generations[level].isEmpty();
logger.debug("Choosing candidates for L{}", level);
if (level == 0)
{
// L0 is the dumping ground for new sstables which thus may overlap each other.
//
// We treat L0 compactions specially:
// 1a. add sstables to the candidate set until we have at least maxSSTableSizeInMB
// 1b. prefer choosing older sstables as candidates, to newer ones
// 1c. any L0 sstables that overlap a candidate, will also become candidates
// 2. At most MAX_COMPACTING_L0 sstables from L0 will be compacted at once
// 3. If total candidate size is less than maxSSTableSizeInMB, we won't bother compacting with L1,
// and the result of the compaction will stay in L0 instead of being promoted (see promote())
//
// Note that we ignore suspect-ness of L1 sstables here, since if an L1 sstable is suspect we're
// basically screwed, since we expect all or most L0 sstables to overlap with each L1 sstable.
// So if an L1 sstable is suspect we can't do much besides try anyway and hope for the best.
Set<SSTableReader> candidates = new HashSet<SSTableReader>();
Set<SSTableReader> remaining = new HashSet<SSTableReader>(generations[0]);
List<SSTableReader> ageSortedSSTables = new ArrayList<SSTableReader>(generations[0]);
Collections.sort(ageSortedSSTables, SSTable.maxTimestampComparator);
for (SSTableReader sstable : ageSortedSSTables)
{
if (candidates.contains(sstable))
continue;
for (SSTableReader newCandidate : Sets.union(Collections.singleton(sstable), overlapping(sstable, remaining)))
{
if (!newCandidate.isMarkedSuspect())
{
candidates.add(newCandidate);
remaining.remove(newCandidate);
}
}
if (candidates.size() > MAX_COMPACTING_L0)
{
// limit to only the MAX_COMPACTING_L0 oldest candidates
List<SSTableReader> ageSortedCandidates = new ArrayList<SSTableReader>(candidates);
Collections.sort(ageSortedCandidates, SSTable.maxTimestampComparator);
candidates = new HashSet<SSTableReader>(ageSortedCandidates.subList(0, MAX_COMPACTING_L0));
break;
}
}
if (SSTable.getTotalBytes(candidates) > maxSSTableSizeInBytes)
{
// add sstables from L1 that overlap candidates
candidates.addAll(overlapping(candidates, generations[1]));
}
return candidates;
}
// for non-L0 compactions, pick up where we left off last time
Collections.sort(generations[level], SSTable.sstableComparator);
int start = 0; // handles case where the prior compaction touched the very last range
for (int i = 0; i < generations[level].size(); i++)
{
SSTableReader sstable = generations[level].get(i);
if (sstable.first.compareTo(lastCompactedKeys[level]) > 0)
{
start = i;
break;
}
}
// look for a non-suspect table to compact with, starting with where we left off last time,
// and wrapping back to the beginning of the generation if necessary
int i = start;
outer:
while (true)
{
SSTableReader sstable = generations[level].get(i);
Set<SSTableReader> candidates = Sets.union(Collections.singleton(sstable), overlapping(sstable, generations[(level + 1)]));
for (SSTableReader candidate : candidates)
{
if (candidate.isMarkedSuspect())
{
i = (i + 1) % generations[level].size();
if (i == start)
break outer;
continue outer;
}
}
return candidates;
}
// all the sstables were suspect or overlapped with something suspect
return Collections.emptyList();
}
public static File tryGetManifest(ColumnFamilyStore cfs)
{
return cfs.directories.tryGetLeveledManifest();
}
public synchronized void serialize()
{
File manifestFile = cfs.directories.getOrCreateLeveledManifest();
File oldFile = new File(manifestFile.getPath().replace(EXTENSION, "-old.json"));
File tmpFile = new File(manifestFile.getPath().replace(EXTENSION, "-tmp.json"));
JsonFactory f = new JsonFactory();
try
{
JsonGenerator g = f.createJsonGenerator(tmpFile, JsonEncoding.UTF8);
g.useDefaultPrettyPrinter();
g.writeStartObject();
g.writeArrayFieldStart("generations");
for (int level = 0; level < generations.length; level++)
{
g.writeStartObject();
g.writeNumberField("generation", level);
g.writeArrayFieldStart("members");
for (SSTableReader ssTableReader : generations[level])
g.writeNumber(ssTableReader.descriptor.generation);
g.writeEndArray(); // members
g.writeEndObject(); // generation
}
g.writeEndArray(); // for field generations
g.writeEndObject(); // write global object
g.close();
if (oldFile.exists() && manifestFile.exists())
FileUtils.deleteWithConfirm(oldFile);
if (manifestFile.exists())
FileUtils.renameWithConfirm(manifestFile, oldFile);
assert tmpFile.exists();
FileUtils.renameWithConfirm(tmpFile, manifestFile);
logger.debug("Saved manifest {}", manifestFile);
}
catch (IOException e)
{
throw new IOError(e);
}
}
@Override
public String toString()
{
return "Manifest@" + hashCode();
}
public int getLevelCount()
{
for (int i = generations.length - 1; i >= 0; i--)
{
if (generations[i].size() > 0)
return i;
}
return 0;
}
public List<SSTableReader> getLevel(int i)
{
return generations[i];
}
public synchronized int getEstimatedTasks()
{
long tasks = 0;
long[] estimated = new long[generations.length];
for (int i = generations.length - 1; i >= 0; i--)
{
List<SSTableReader> sstables = generations[i];
estimated[i] = Math.max(0L, SSTableReader.getTotalBytes(sstables) - maxBytesForLevel(i)) / maxSSTableSizeInBytes;
tasks += estimated[i];
}
logger.debug("Estimating {} compactions to do for {}.{}",
new Object[] {Arrays.toString(estimated), cfs.table.name, cfs.columnFamily});
return Ints.checkedCast(tasks);
}
}
| fix infinite recompaction in L0
| src/java/org/apache/cassandra/db/compaction/LeveledManifest.java | fix infinite recompaction in L0 | <ide><path>rc/java/org/apache/cassandra/db/compaction/LeveledManifest.java
<ide> candidates.addAll(overlapping(candidates, generations[1]));
<ide> }
<ide>
<del> return candidates;
<add> return candidates.size() > 1 ? candidates : Collections.<SSTableReader>emptyList();
<ide> }
<ide>
<ide> // for non-L0 compactions, pick up where we left off last time |
|
Java | apache-2.0 | b6a9cf5ad8c9611af83717c6bdea963286fe89d2 | 0 | allenz8512/AndroidAppLog | package me.allenz.androidapplog;
import android.util.Log;
public abstract class AbstractLogger implements Logger {
protected static final String STRING_NULL = "null";
protected String name;
protected LogLevel level;
protected String tag;
protected boolean showThreadName;
public AbstractLogger(final String name) {
this(name, Configure.DEFAULT_ROOT_LOG_LEVEL, null, false);
}
public AbstractLogger(final String name, final LogLevel level,
final String tag, final boolean showThreadName) {
this.name = name;
this.level = level;
this.tag = tag;
this.showThreadName = showThreadName;
}
@Override
public String getName() {
return name;
}
@Override
public LogLevel getLogLevel() {
return level;
}
@Override
public void setLogLevel(final LogLevel level) {
this.level = level;
}
@Override
public String getTag() {
return tag;
}
@Override
public void setTag(final String tag) {
this.tag = tag;
}
@Override
public boolean isShowThreadName() {
return showThreadName;
}
@Override
public void setShowThreadName(final boolean show) {
showThreadName = show;
}
@Override
public void verbose(final String format, final Object... args) {
println(LogLevel.VERBOSE, null, format, args);
}
@Override
public void verbose(final Throwable t) {
println(LogLevel.VERBOSE, t, null);
}
@Override
public void verbose(final Throwable t, final String format,
final Object... args) {
println(LogLevel.VERBOSE, t, null);
}
@Override
public void verbose(final String message) {
println(LogLevel.VERBOSE, null, message);
}
@Override
public void verbose(final Throwable t, final String message) {
println(LogLevel.VERBOSE, t, message);
}
@Override
public void verbose(final Object obj) {
final String message = obj == null ? STRING_NULL : obj.toString();
println(LogLevel.VERBOSE, null, message);
}
@Override
public void debug(final String format, final Object... args) {
println(LogLevel.DEBUG, null, format, args);
}
@Override
public void debug(final Throwable t) {
println(LogLevel.DEBUG, t, null);
}
@Override
public void debug(final Throwable t, final String format,
final Object... args) {
println(LogLevel.DEBUG, t, format, args);
}
@Override
public void debug(final String message) {
println(LogLevel.DEBUG, null, message);
}
@Override
public void debug(final Throwable t, final String message) {
println(LogLevel.DEBUG, t, message);
}
@Override
public void debug(final Object obj) {
final String message = obj == null ? STRING_NULL : obj.toString();
println(LogLevel.DEBUG, null, message);
}
@Override
public void info(final String format, final Object... args) {
println(LogLevel.INFO, null, format, args);
}
@Override
public void info(final Throwable t) {
println(LogLevel.INFO, t, null);
}
@Override
public void info(final Throwable t, final String format,
final Object... args) {
println(LogLevel.INFO, t, format, args);
}
@Override
public void info(final String message) {
println(LogLevel.INFO, null, message);
}
@Override
public void info(final Throwable t, final String message) {
println(LogLevel.INFO, t, message);
}
@Override
public void info(final Object obj) {
final String message = obj == null ? STRING_NULL : obj.toString();
println(LogLevel.INFO, null, message);
}
@Override
public void warn(final String format, final Object... args) {
println(LogLevel.WARN, null, format, args);
}
@Override
public void warn(final Throwable t) {
println(LogLevel.WARN, t, null);
}
@Override
public void warn(final Throwable t, final String format,
final Object... args) {
println(LogLevel.WARN, t, format, args);
}
@Override
public void warn(final String message) {
println(LogLevel.WARN, null, message);
}
@Override
public void warn(final Throwable t, final String message) {
println(LogLevel.WARN, t, message);
}
@Override
public void warn(final Object obj) {
final String message = obj == null ? STRING_NULL : obj.toString();
println(LogLevel.WARN, null, message);
}
@Override
public void error(final String format, final Object... args) {
println(LogLevel.ERROR, null, format, args);
}
@Override
public void error(final Throwable t) {
println(LogLevel.ERROR, t, null);
}
@Override
public void error(final Throwable t, final String format,
final Object... args) {
println(LogLevel.ERROR, t, format, args);
}
@Override
public void error(final String message) {
println(LogLevel.ERROR, null, message);
}
@Override
public void error(final Throwable t, final String message) {
println(LogLevel.ERROR, t, message);
}
@Override
public void error(final Object obj) {
final String message = obj == null ? STRING_NULL : obj.toString();
println(LogLevel.ERROR, null, message);
}
@Override
public void wtf(final String format, final Object... args) {
println(LogLevel.ASSERT, null, format, args);
}
@Override
public void wtf(final Throwable t) {
println(LogLevel.ASSERT, t, null);
}
@Override
public void wtf(final Throwable t, final String format,
final Object... args) {
println(LogLevel.ASSERT, t, format, args);
}
@Override
public void wtf(final String message) {
println(LogLevel.ASSERT, null, message);
}
@Override
public void wtf(final Throwable t, final String message) {
println(LogLevel.ASSERT, t, message);
}
@Override
public void wtf(final Object obj) {
final String message = obj == null ? STRING_NULL : obj.toString();
println(LogLevel.ASSERT, null, message);
}
protected LogEvent buidLogEvent(final LogLevel level, final Throwable t,
final String format, final Object... args) {
String message = null;
if (format != null && format.length() > 0) {
message = (args != null && args.length > 0) ? String.format(format,
args) : format;
}
if (t != null) {
message = message != null ? message + "\n"
+ Log.getStackTraceString(t) : Log.getStackTraceString(t);
}
String tag;
if (showThreadName) {
final StringBuilder sb = new StringBuilder();
sb.append("[").append(Thread.currentThread().getName()).append("]")
.append(this.tag);
tag = sb.toString();
} else {
tag = this.tag;
}
return new LogEvent(level, tag, message);
}
protected abstract void println(final LogLevel level, final Throwable t,
final String format, final Object... args);
@Override
public String toString() {
return "Logger [name=" + name + ", level=" + level + ", tag=" + tag
+ ", showThreadName=" + showThreadName + "]";
}
}
| src/main/java/me/allenz/androidapplog/AbstractLogger.java | package me.allenz.androidapplog;
import android.util.Log;
public abstract class AbstractLogger implements Logger {
protected String name;
protected LogLevel level;
protected String tag;
protected boolean showThreadName;
public AbstractLogger(final String name){
this(name, Configure.DEFAULT_ROOT_LOG_LEVEL, null, false);
}
public AbstractLogger(final String name, final LogLevel level, final String tag, final boolean showThreadName){
this.name = name;
this.level = level;
this.tag = tag;
this.showThreadName = showThreadName;
}
@Override
public String getName() {
return name;
}
@Override
public LogLevel getLogLevel() {
return level;
}
@Override
public void setLogLevel(final LogLevel level) {
this.level = level;
}
@Override
public String getTag() {
return tag;
}
@Override
public void setTag(final String tag) {
this.tag = tag;
}
@Override
public boolean isShowThreadName() {
return showThreadName;
}
@Override
public void setShowThreadName(final boolean show) {
showThreadName = show;
}
@Override
public void verbose(final String format, final Object... args) {
println(LogLevel.VERBOSE, null, format, args);
}
@Override
public void verbose(final Throwable t) {
println(LogLevel.VERBOSE, t, null);
}
@Override
public void verbose(final Throwable t, final String format,
final Object... args) {
println(LogLevel.VERBOSE, t, null);
}
@Override
public void verbose(final String message) {
println(LogLevel.VERBOSE, null, message);
}
@Override
public void verbose(final Throwable t, final String message) {
println(LogLevel.VERBOSE, t, message);
}
@Override
public void verbose(final Object obj) {
println(LogLevel.VERBOSE, null, obj.toString());
}
@Override
public void debug(final String format, final Object... args) {
println(LogLevel.DEBUG, null, format, args);
}
@Override
public void debug(final Throwable t) {
println(LogLevel.DEBUG, t, null);
}
@Override
public void debug(final Throwable t, final String format,
final Object... args) {
println(LogLevel.DEBUG, t, format, args);
}
@Override
public void debug(final String message) {
println(LogLevel.DEBUG, null, message);
}
@Override
public void debug(final Throwable t, final String message) {
println(LogLevel.DEBUG, t, message);
}
@Override
public void debug(final Object obj) {
println(LogLevel.DEBUG, null, obj.toString());
}
@Override
public void info(final String format, final Object... args) {
println(LogLevel.INFO, null, format, args);
}
@Override
public void info(final Throwable t) {
println(LogLevel.INFO, t, null);
}
@Override
public void info(final Throwable t, final String format,
final Object... args) {
println(LogLevel.INFO, t, format, args);
}
@Override
public void info(final String message) {
println(LogLevel.INFO, null, message);
}
@Override
public void info(final Throwable t, final String message) {
println(LogLevel.INFO, t, message);
}
@Override
public void info(final Object obj) {
println(LogLevel.INFO, null, obj.toString());
}
@Override
public void warn(final String format, final Object... args) {
println(LogLevel.WARN, null, format, args);
}
@Override
public void warn(final Throwable t) {
println(LogLevel.WARN, t, null);
}
@Override
public void warn(final Throwable t, final String format,
final Object... args) {
println(LogLevel.WARN, t, format, args);
}
@Override
public void warn(final String message) {
println(LogLevel.WARN, null, message);
}
@Override
public void warn(final Throwable t, final String message) {
println(LogLevel.WARN, t, message);
}
@Override
public void warn(final Object obj) {
println(LogLevel.WARN, null, obj.toString());
}
@Override
public void error(final String format, final Object... args) {
println(LogLevel.ERROR, null, format, args);
}
@Override
public void error(final Throwable t) {
println(LogLevel.ERROR, t, null);
}
@Override
public void error(final Throwable t, final String format,
final Object... args) {
println(LogLevel.ERROR, t, format, args);
}
@Override
public void error(final String message) {
println(LogLevel.ERROR, null, message);
}
@Override
public void error(final Throwable t, final String message) {
println(LogLevel.ERROR, t, message);
}
@Override
public void error(final Object obj) {
println(LogLevel.ERROR, null, obj.toString());
}
@Override
public void wtf(final String format, final Object... args) {
println(LogLevel.ASSERT, null, format, args);
}
@Override
public void wtf(final Throwable t) {
println(LogLevel.ASSERT, t, null);
}
@Override
public void wtf(final Throwable t, final String format,
final Object... args) {
println(LogLevel.ASSERT, t, format, args);
}
@Override
public void wtf(final String message) {
println(LogLevel.ASSERT, null, message);
}
@Override
public void wtf(final Throwable t, final String message) {
println(LogLevel.ASSERT, t, message);
}
@Override
public void wtf(final Object obj) {
println(LogLevel.ASSERT, null, obj.toString());
}
protected LogEvent buidLogEvent(final LogLevel level, final Throwable t,
final String format, final Object... args) {
String message = null;
if (format != null &&
format.length() > 0) {
message = (args != null && args.length > 0)? String.format(
format, args): format;
}
if (t != null) {
message = message != null? message +
"\n"
+ Log.getStackTraceString(t): Log
.getStackTraceString(t);
}
String tag;
if (showThreadName) {
final StringBuilder sb = new StringBuilder();
sb.append("[").append(Thread.currentThread().getName())
.append("]").append(this.tag);
tag = sb.toString();
} else {
tag = this.tag;
}
return new LogEvent(level, tag, message);
}
protected abstract void println(final LogLevel level, final Throwable t,
final String format, final Object... args);
@Override
public String toString() {
return "Logger [name=" +
name + ", level=" + level + ", tag=" + tag + ", showThreadName=" + showThreadName + "]";
}
}
| Fixed #4 : Throw NullPointerException when the object to log is Null | src/main/java/me/allenz/androidapplog/AbstractLogger.java | Fixed #4 : Throw NullPointerException when the object to log is Null | <ide><path>rc/main/java/me/allenz/androidapplog/AbstractLogger.java
<ide>
<ide> public abstract class AbstractLogger implements Logger {
<ide>
<del> protected String name;
<del>
<del> protected LogLevel level;
<del>
<del> protected String tag;
<del>
<del> protected boolean showThreadName;
<del>
<del> public AbstractLogger(final String name){
<del> this(name, Configure.DEFAULT_ROOT_LOG_LEVEL, null, false);
<del> }
<del>
<del> public AbstractLogger(final String name, final LogLevel level, final String tag, final boolean showThreadName){
<del> this.name = name;
<del> this.level = level;
<del> this.tag = tag;
<del> this.showThreadName = showThreadName;
<del> }
<del>
<del> @Override
<del> public String getName() {
<del> return name;
<del> }
<del>
<del> @Override
<del> public LogLevel getLogLevel() {
<del> return level;
<del> }
<del>
<del> @Override
<del> public void setLogLevel(final LogLevel level) {
<del> this.level = level;
<del> }
<del>
<del> @Override
<del> public String getTag() {
<del> return tag;
<del> }
<del>
<del> @Override
<del> public void setTag(final String tag) {
<del> this.tag = tag;
<del> }
<del>
<del> @Override
<del> public boolean isShowThreadName() {
<del> return showThreadName;
<del> }
<del>
<del> @Override
<del> public void setShowThreadName(final boolean show) {
<del> showThreadName = show;
<del> }
<del>
<del> @Override
<del> public void verbose(final String format, final Object... args) {
<del> println(LogLevel.VERBOSE, null, format, args);
<del> }
<del>
<del> @Override
<del> public void verbose(final Throwable t) {
<del> println(LogLevel.VERBOSE, t, null);
<del> }
<del>
<del> @Override
<del> public void verbose(final Throwable t, final String format,
<del> final Object... args) {
<del> println(LogLevel.VERBOSE, t, null);
<del> }
<del>
<del> @Override
<del> public void verbose(final String message) {
<del> println(LogLevel.VERBOSE, null, message);
<del> }
<del>
<del> @Override
<del> public void verbose(final Throwable t, final String message) {
<del> println(LogLevel.VERBOSE, t, message);
<del> }
<del>
<del> @Override
<del> public void verbose(final Object obj) {
<del> println(LogLevel.VERBOSE, null, obj.toString());
<del> }
<del>
<del> @Override
<del> public void debug(final String format, final Object... args) {
<del> println(LogLevel.DEBUG, null, format, args);
<del> }
<del>
<del> @Override
<del> public void debug(final Throwable t) {
<del> println(LogLevel.DEBUG, t, null);
<del> }
<del>
<del> @Override
<del> public void debug(final Throwable t, final String format,
<del> final Object... args) {
<del> println(LogLevel.DEBUG, t, format, args);
<del> }
<del>
<del> @Override
<del> public void debug(final String message) {
<del> println(LogLevel.DEBUG, null, message);
<del> }
<del>
<del> @Override
<del> public void debug(final Throwable t, final String message) {
<del> println(LogLevel.DEBUG, t, message);
<del> }
<del>
<del> @Override
<del> public void debug(final Object obj) {
<del> println(LogLevel.DEBUG, null, obj.toString());
<del> }
<del>
<del> @Override
<del> public void info(final String format, final Object... args) {
<del> println(LogLevel.INFO, null, format, args);
<del> }
<del>
<del> @Override
<del> public void info(final Throwable t) {
<del> println(LogLevel.INFO, t, null);
<del> }
<del>
<del> @Override
<del> public void info(final Throwable t, final String format,
<del> final Object... args) {
<del> println(LogLevel.INFO, t, format, args);
<del> }
<del>
<del> @Override
<del> public void info(final String message) {
<del> println(LogLevel.INFO, null, message);
<del> }
<del>
<del> @Override
<del> public void info(final Throwable t, final String message) {
<del> println(LogLevel.INFO, t, message);
<del> }
<del>
<del> @Override
<del> public void info(final Object obj) {
<del> println(LogLevel.INFO, null, obj.toString());
<del> }
<del>
<del> @Override
<del> public void warn(final String format, final Object... args) {
<del> println(LogLevel.WARN, null, format, args);
<del> }
<del>
<del> @Override
<del> public void warn(final Throwable t) {
<del> println(LogLevel.WARN, t, null);
<del> }
<del>
<del> @Override
<del> public void warn(final Throwable t, final String format,
<del> final Object... args) {
<del> println(LogLevel.WARN, t, format, args);
<del> }
<del>
<del> @Override
<del> public void warn(final String message) {
<del> println(LogLevel.WARN, null, message);
<del> }
<del>
<del> @Override
<del> public void warn(final Throwable t, final String message) {
<del> println(LogLevel.WARN, t, message);
<del> }
<del>
<del> @Override
<del> public void warn(final Object obj) {
<del> println(LogLevel.WARN, null, obj.toString());
<del> }
<del>
<del> @Override
<del> public void error(final String format, final Object... args) {
<del> println(LogLevel.ERROR, null, format, args);
<del> }
<del>
<del> @Override
<del> public void error(final Throwable t) {
<del> println(LogLevel.ERROR, t, null);
<del> }
<del>
<del> @Override
<del> public void error(final Throwable t, final String format,
<del> final Object... args) {
<del> println(LogLevel.ERROR, t, format, args);
<del> }
<del>
<del> @Override
<del> public void error(final String message) {
<del> println(LogLevel.ERROR, null, message);
<del> }
<del>
<del> @Override
<del> public void error(final Throwable t, final String message) {
<del> println(LogLevel.ERROR, t, message);
<del> }
<del>
<del> @Override
<del> public void error(final Object obj) {
<del> println(LogLevel.ERROR, null, obj.toString());
<del> }
<del>
<del> @Override
<del> public void wtf(final String format, final Object... args) {
<del> println(LogLevel.ASSERT, null, format, args);
<del> }
<del>
<del> @Override
<del> public void wtf(final Throwable t) {
<del> println(LogLevel.ASSERT, t, null);
<del> }
<del>
<del> @Override
<del> public void wtf(final Throwable t, final String format,
<del> final Object... args) {
<del> println(LogLevel.ASSERT, t, format, args);
<del> }
<del>
<del> @Override
<del> public void wtf(final String message) {
<del> println(LogLevel.ASSERT, null, message);
<del> }
<del>
<del> @Override
<del> public void wtf(final Throwable t, final String message) {
<del> println(LogLevel.ASSERT, t, message);
<del> }
<del>
<del> @Override
<del> public void wtf(final Object obj) {
<del> println(LogLevel.ASSERT, null, obj.toString());
<del> }
<del>
<del> protected LogEvent buidLogEvent(final LogLevel level, final Throwable t,
<del> final String format, final Object... args) {
<del> String message = null;
<del> if (format != null &&
<del> format.length() > 0) {
<del> message = (args != null && args.length > 0)? String.format(
<del> format, args): format;
<del> }
<del> if (t != null) {
<del> message = message != null? message +
<del> "\n"
<del> + Log.getStackTraceString(t): Log
<del> .getStackTraceString(t);
<del> }
<del> String tag;
<del> if (showThreadName) {
<del> final StringBuilder sb = new StringBuilder();
<del> sb.append("[").append(Thread.currentThread().getName())
<del> .append("]").append(this.tag);
<del> tag = sb.toString();
<del> } else {
<del> tag = this.tag;
<del> }
<del> return new LogEvent(level, tag, message);
<del> }
<del>
<del> protected abstract void println(final LogLevel level, final Throwable t,
<del> final String format, final Object... args);
<del>
<del> @Override
<del> public String toString() {
<del> return "Logger [name=" +
<del> name + ", level=" + level + ", tag=" + tag + ", showThreadName=" + showThreadName + "]";
<del> }
<add> protected static final String STRING_NULL = "null";
<add>
<add> protected String name;
<add>
<add> protected LogLevel level;
<add>
<add> protected String tag;
<add>
<add> protected boolean showThreadName;
<add>
<add> public AbstractLogger(final String name) {
<add> this(name, Configure.DEFAULT_ROOT_LOG_LEVEL, null, false);
<add> }
<add>
<add> public AbstractLogger(final String name, final LogLevel level,
<add> final String tag, final boolean showThreadName) {
<add> this.name = name;
<add> this.level = level;
<add> this.tag = tag;
<add> this.showThreadName = showThreadName;
<add> }
<add>
<add> @Override
<add> public String getName() {
<add> return name;
<add> }
<add>
<add> @Override
<add> public LogLevel getLogLevel() {
<add> return level;
<add> }
<add>
<add> @Override
<add> public void setLogLevel(final LogLevel level) {
<add> this.level = level;
<add> }
<add>
<add> @Override
<add> public String getTag() {
<add> return tag;
<add> }
<add>
<add> @Override
<add> public void setTag(final String tag) {
<add> this.tag = tag;
<add> }
<add>
<add> @Override
<add> public boolean isShowThreadName() {
<add> return showThreadName;
<add> }
<add>
<add> @Override
<add> public void setShowThreadName(final boolean show) {
<add> showThreadName = show;
<add> }
<add>
<add> @Override
<add> public void verbose(final String format, final Object... args) {
<add> println(LogLevel.VERBOSE, null, format, args);
<add> }
<add>
<add> @Override
<add> public void verbose(final Throwable t) {
<add> println(LogLevel.VERBOSE, t, null);
<add> }
<add>
<add> @Override
<add> public void verbose(final Throwable t, final String format,
<add> final Object... args) {
<add> println(LogLevel.VERBOSE, t, null);
<add> }
<add>
<add> @Override
<add> public void verbose(final String message) {
<add> println(LogLevel.VERBOSE, null, message);
<add> }
<add>
<add> @Override
<add> public void verbose(final Throwable t, final String message) {
<add> println(LogLevel.VERBOSE, t, message);
<add> }
<add>
<add> @Override
<add> public void verbose(final Object obj) {
<add> final String message = obj == null ? STRING_NULL : obj.toString();
<add> println(LogLevel.VERBOSE, null, message);
<add> }
<add>
<add> @Override
<add> public void debug(final String format, final Object... args) {
<add> println(LogLevel.DEBUG, null, format, args);
<add> }
<add>
<add> @Override
<add> public void debug(final Throwable t) {
<add> println(LogLevel.DEBUG, t, null);
<add> }
<add>
<add> @Override
<add> public void debug(final Throwable t, final String format,
<add> final Object... args) {
<add> println(LogLevel.DEBUG, t, format, args);
<add> }
<add>
<add> @Override
<add> public void debug(final String message) {
<add> println(LogLevel.DEBUG, null, message);
<add> }
<add>
<add> @Override
<add> public void debug(final Throwable t, final String message) {
<add> println(LogLevel.DEBUG, t, message);
<add> }
<add>
<add> @Override
<add> public void debug(final Object obj) {
<add> final String message = obj == null ? STRING_NULL : obj.toString();
<add> println(LogLevel.DEBUG, null, message);
<add> }
<add>
<add> @Override
<add> public void info(final String format, final Object... args) {
<add> println(LogLevel.INFO, null, format, args);
<add> }
<add>
<add> @Override
<add> public void info(final Throwable t) {
<add> println(LogLevel.INFO, t, null);
<add> }
<add>
<add> @Override
<add> public void info(final Throwable t, final String format,
<add> final Object... args) {
<add> println(LogLevel.INFO, t, format, args);
<add> }
<add>
<add> @Override
<add> public void info(final String message) {
<add> println(LogLevel.INFO, null, message);
<add> }
<add>
<add> @Override
<add> public void info(final Throwable t, final String message) {
<add> println(LogLevel.INFO, t, message);
<add> }
<add>
<add> @Override
<add> public void info(final Object obj) {
<add> final String message = obj == null ? STRING_NULL : obj.toString();
<add> println(LogLevel.INFO, null, message);
<add> }
<add>
<add> @Override
<add> public void warn(final String format, final Object... args) {
<add> println(LogLevel.WARN, null, format, args);
<add> }
<add>
<add> @Override
<add> public void warn(final Throwable t) {
<add> println(LogLevel.WARN, t, null);
<add> }
<add>
<add> @Override
<add> public void warn(final Throwable t, final String format,
<add> final Object... args) {
<add> println(LogLevel.WARN, t, format, args);
<add> }
<add>
<add> @Override
<add> public void warn(final String message) {
<add> println(LogLevel.WARN, null, message);
<add> }
<add>
<add> @Override
<add> public void warn(final Throwable t, final String message) {
<add> println(LogLevel.WARN, t, message);
<add> }
<add>
<add> @Override
<add> public void warn(final Object obj) {
<add> final String message = obj == null ? STRING_NULL : obj.toString();
<add> println(LogLevel.WARN, null, message);
<add> }
<add>
<add> @Override
<add> public void error(final String format, final Object... args) {
<add> println(LogLevel.ERROR, null, format, args);
<add> }
<add>
<add> @Override
<add> public void error(final Throwable t) {
<add> println(LogLevel.ERROR, t, null);
<add> }
<add>
<add> @Override
<add> public void error(final Throwable t, final String format,
<add> final Object... args) {
<add> println(LogLevel.ERROR, t, format, args);
<add> }
<add>
<add> @Override
<add> public void error(final String message) {
<add> println(LogLevel.ERROR, null, message);
<add> }
<add>
<add> @Override
<add> public void error(final Throwable t, final String message) {
<add> println(LogLevel.ERROR, t, message);
<add> }
<add>
<add> @Override
<add> public void error(final Object obj) {
<add> final String message = obj == null ? STRING_NULL : obj.toString();
<add> println(LogLevel.ERROR, null, message);
<add> }
<add>
<add> @Override
<add> public void wtf(final String format, final Object... args) {
<add> println(LogLevel.ASSERT, null, format, args);
<add> }
<add>
<add> @Override
<add> public void wtf(final Throwable t) {
<add> println(LogLevel.ASSERT, t, null);
<add> }
<add>
<add> @Override
<add> public void wtf(final Throwable t, final String format,
<add> final Object... args) {
<add> println(LogLevel.ASSERT, t, format, args);
<add> }
<add>
<add> @Override
<add> public void wtf(final String message) {
<add> println(LogLevel.ASSERT, null, message);
<add> }
<add>
<add> @Override
<add> public void wtf(final Throwable t, final String message) {
<add> println(LogLevel.ASSERT, t, message);
<add> }
<add>
<add> @Override
<add> public void wtf(final Object obj) {
<add> final String message = obj == null ? STRING_NULL : obj.toString();
<add> println(LogLevel.ASSERT, null, message);
<add> }
<add>
<add> protected LogEvent buidLogEvent(final LogLevel level, final Throwable t,
<add> final String format, final Object... args) {
<add> String message = null;
<add> if (format != null && format.length() > 0) {
<add> message = (args != null && args.length > 0) ? String.format(format,
<add> args) : format;
<add> }
<add> if (t != null) {
<add> message = message != null ? message + "\n"
<add> + Log.getStackTraceString(t) : Log.getStackTraceString(t);
<add> }
<add> String tag;
<add> if (showThreadName) {
<add> final StringBuilder sb = new StringBuilder();
<add> sb.append("[").append(Thread.currentThread().getName()).append("]")
<add> .append(this.tag);
<add> tag = sb.toString();
<add> } else {
<add> tag = this.tag;
<add> }
<add> return new LogEvent(level, tag, message);
<add> }
<add>
<add> protected abstract void println(final LogLevel level, final Throwable t,
<add> final String format, final Object... args);
<add>
<add> @Override
<add> public String toString() {
<add> return "Logger [name=" + name + ", level=" + level + ", tag=" + tag
<add> + ", showThreadName=" + showThreadName + "]";
<add> }
<ide>
<ide> } |
|
Java | lgpl-2.1 | 5b4c957f25cebcd1247adf61ea4aa32c992c8b8b | 0 | RapidProjectH2020/rapid-common | /*******************************************************************************
* Copyright (C) 2015, 2016 RAPID EU Project
*
* 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 eu.project.rapid.common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.regex.Pattern;
import eu.project.rapid.common.RapidMessages.AnimationMsg;
/**
* These are some utilities to be used on the Rapid project.
* In particular, some important functions are used by the AS and AC.
* @author sokol
*/
public class RapidUtils {
private static final String TAG = "RapidUtils";
private static final String IPADDRESS_PATTERN =
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
private static boolean demoAnimate = true;
private static final Thread demoServerThread;
private static BlockingQueue<String> commandQueue = new ArrayBlockingQueue<String>(1000);
private static String demoServerIp;
private static int demoServerPort;
static {
demoServerThread = new Thread() {
public void run() {
System.out.println("Started thread that consumes the commands to send to the Demo server");
while (true) {
try {
String cmd = commandQueue.take();
sendAnimationMsg(cmd);
} catch (InterruptedException e) {
}
}
}
};
demoServerThread.start();
}
/**
* Utility to execute a shell command on a Mac OS.
*
* @param command
* @param asRoot
* @param password
* @return
*/
public static String executeCommand(String command, boolean asRoot, String password) {
Process p = null;
String[] cmd = new String[] {"/bin/bash", "-c", command};
try {
if (asRoot) {
cmd = new String[] {"/bin/bash", "-c", "echo " + password + "|sudo -S " + command};
}
System.out.println("Executing command: " + command);
p = Runtime.getRuntime().exec(cmd);
// you can pass the system command or a script to exec command.
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
// read the output from the command
StringBuilder sb = new StringBuilder();
String s = "";
while ((s = stdInput.readLine()) != null) {
// System.out.println("Std OUT: "+s);
sb.append(s);
}
while ((s = stdError.readLine()) != null) {
System.out.println("Std ERROR : " + s);
}
System.out.println(sb.toString());
stdInput.close();
stdError.close();
writer.close();
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String executeCommand(String command) {
return executeCommand(command, false, null);
}
public static byte[] serialize(Object obj) throws IOException {
byte[] serializedObj;
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
try {
o.writeObject(obj);
o.flush();
serializedObj = b.toByteArray();
} finally {
o.close();
}
return serializedObj;
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
return RapidUtils.deserialize(bytes, 0, bytes.length);
}
public static Object deserialize(byte[] bytes, int offset, int length)
throws IOException, ClassNotFoundException {
Object obj;
ByteArrayInputStream b = new ByteArrayInputStream(bytes, offset, length);
ObjectInputStream o = new ObjectInputStream(b);
obj = o.readObject();
o.close();
return obj;
}
/**
* Connect to the animation server and send the messages that represent the sequence of
* operations.
*
* @param config
* @param millis
* @param msgs
*/
public static synchronized void sendAnimationMsg(Configuration config, String msg) {
sendAnimationMsg(config.getAnimationServerIp(), config.getAnimationServerPort(), msg);
}
public static synchronized void sendAnimationMsg(Configuration config, AnimationMsg msg) {
sendAnimationMsg(config.getAnimationServerIp(), config.getAnimationServerPort(), msg.toString());
}
/**
* Connect to the animation server and send the messages that represent the sequence of
* operations.
*
* @param config
* @param millis
* @param msgs
*/
public static synchronized void sendAnimationMsg(final String ip, final int port,
final String msg) {
if (demoAnimate) {
RapidUtils.demoServerIp = ip;
RapidUtils.demoServerPort = port;
boolean added = false;
while (!added) {
try {
commandQueue.put(msg);
added = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void closeQuietly(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(ObjectInputStream oIs) {
if (oIs != null) {
try {
oIs.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(ObjectOutputStream oOs) {
if (oOs != null) {
try {
oOs.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
private static void sendAnimationMsg(String msg) {
Socket socket = null;
PrintWriter pout = null;
try {
System.out.println(TAG + " - Sending animation msg: " + msg + " to " + demoServerIp + ":"
+ demoServerPort);
socket = new Socket(demoServerIp, demoServerPort);
pout = new PrintWriter(socket.getOutputStream(), true);
pout.print(msg);
} catch (Exception e) {
// System.err.println("Could not connect to animation server: " + demoServerIp + ":"
// + demoServerPort + ": " + e);
} finally {
if (pout != null) {
pout.close();
}
closeQuietly(socket);
}
}
public static boolean isPrimaryAnimationServerRunning(String ip, int port) {
Socket socket = null;
PrintWriter pout = null;
try {
System.out.println(TAG + " - Connecting with primary server " + ip + ":" + port);
socket = new Socket(ip, port);
pout = new PrintWriter(socket.getOutputStream(), true);
pout.print(AnimationMsg.PING);
return true;
} catch (Exception e) {
// System.err.println("Could not connect to animation server: " + ip + ":"
// + port + ": " + e);
} finally {
if (pout != null) {
pout.close();
}
closeQuietly(socket);
}
return false;
}
/**
* Validate ip address with regular expression
* @param ip ip address for validation
* @return true valid ip address, false invalid ip address
*/
public static boolean validateIpAddress(final String ip){
Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
return pattern.matcher(ip).matches();
}
public static String getVmIpLinux() {
String localIpAddress = "";
Enumeration<NetworkInterface> e;
try {
e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration<InetAddress> ee = n.getInetAddresses();
boolean stop = false;
while (ee.hasMoreElements()) {
InetAddress i = (InetAddress) ee.nextElement();
if (i.getHostAddress().startsWith("10.0.")) {
localIpAddress = i.getHostAddress();
stop = true;
break;
}
}
if (stop)
break;
}
} catch (SocketException e1) {
System.err.println("Error while getting VM IP: " + e1);
}
return localIpAddress;
}
/**
* Connects to the DS and returns the IP of the demo animation server.
* @param dsIp
* @param dsPort
* @return IP of the demo animation server or null.
*/
public static String getDemoAnimationServerIpFromDs(String dsIp, int dsPort) {
String ip = null;
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
socket = new Socket(dsIp, dsPort);
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
oos.writeByte(RapidMessages.GET_DEMO_SERVER_IP_DS);
oos.flush();
ip = ois.readUTF();
}catch (IOException e) {
System.err.println("Could not connect to DS for getting demo server IP: " + e);
} finally {
closeQuietly(ois);
closeQuietly(oos);
closeQuietly(socket);
}
return ip;
}
}
| src/eu/project/rapid/common/RapidUtils.java | /*******************************************************************************
* Copyright (C) 2015, 2016 RAPID EU Project
*
* 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 eu.project.rapid.common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.regex.Pattern;
import eu.project.rapid.common.RapidMessages.AnimationMsg;
/**
* These are some utilities to be used on the Rapid project.
* In particular, some important functions are used by the AS and AC.
* @author sokol
*/
public class RapidUtils {
private static final String TAG = "RapidUtils";
private static final String IPADDRESS_PATTERN =
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
private static boolean demoAnimate = true;
private static final Thread demoServerThread;
private static BlockingQueue<String> commandQueue = new ArrayBlockingQueue<String>(1000);
private static String demoServerIp;
private static int demoServerPort;
static {
demoServerThread = new Thread() {
public void run() {
System.out.println("Started thread that consumes the commands to send to the Demo server");
while (true) {
try {
String cmd = commandQueue.take();
sendAnimationMsg(cmd);
} catch (InterruptedException e) {
}
}
}
};
demoServerThread.start();
}
/**
* Utility to execute a shell command on a Mac OS.
*
* @param command
* @param asRoot
* @param password
* @return
*/
public static String executeCommand(String command, boolean asRoot, String password) {
Process p = null;
String[] cmd = new String[] {"/bin/bash", "-c", command};
try {
if (asRoot) {
cmd = new String[] {"/bin/bash", "-c", "echo " + password + "|sudo -S " + command};
}
System.out.println("Executing command: " + command);
p = Runtime.getRuntime().exec(cmd);
// you can pass the system command or a script to exec command.
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
// read the output from the command
StringBuilder sb = new StringBuilder();
String s = "";
while ((s = stdInput.readLine()) != null) {
// System.out.println("Std OUT: "+s);
sb.append(s);
}
while ((s = stdError.readLine()) != null) {
System.out.println("Std ERROR : " + s);
}
System.out.println(sb.toString());
stdInput.close();
stdError.close();
writer.close();
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String executeCommand(String command) {
return executeCommand(command, false, null);
}
public static byte[] serialize(Object obj) throws IOException {
byte[] serializedObj;
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
try {
o.writeObject(obj);
o.flush();
serializedObj = b.toByteArray();
} finally {
o.close();
}
return serializedObj;
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
return RapidUtils.deserialize(bytes, 0, bytes.length);
}
public static Object deserialize(byte[] bytes, int offset, int length)
throws IOException, ClassNotFoundException {
Object obj;
ByteArrayInputStream b = new ByteArrayInputStream(bytes, offset, length);
ObjectInputStream o = new ObjectInputStream(b);
obj = o.readObject();
o.close();
return obj;
}
/**
* Connect to the animation server and send the messages that represent the sequence of
* operations.
*
* @param config
* @param millis
* @param msgs
*/
public static synchronized void sendAnimationMsg(Configuration config, String msg) {
sendAnimationMsg(config.getAnimationServerIp(), config.getAnimationServerPort(), msg);
}
public static synchronized void sendAnimationMsg(Configuration config, AnimationMsg msg) {
sendAnimationMsg(config.getAnimationServerIp(), config.getAnimationServerPort(), msg.toString());
}
/**
* Connect to the animation server and send the messages that represent the sequence of
* operations.
*
* @param config
* @param millis
* @param msgs
*/
public static synchronized void sendAnimationMsg(final String ip, final int port,
final String msg) {
if (demoAnimate) {
RapidUtils.demoServerIp = ip;
RapidUtils.demoServerPort = port;
boolean added = false;
while (!added) {
try {
commandQueue.put(msg);
added = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void closeQuietly(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(ObjectInputStream oIs) {
if (oIs != null) {
try {
oIs.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(ObjectOutputStream oOs) {
if (oOs != null) {
try {
oOs.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
private static void sendAnimationMsg(String msg) {
Socket socket = null;
PrintWriter pout = null;
try {
System.out.println(TAG + " - Sending animation msg: " + msg + " to " + demoServerIp + ":"
+ demoServerPort);
socket = new Socket(demoServerIp, demoServerPort);
pout = new PrintWriter(socket.getOutputStream(), true);
pout.print(msg);
} catch (Exception e) {
System.err.println("Could not connect to animation server: " + demoServerIp + ":"
+ demoServerPort + ": " + e);
} finally {
if (pout != null) {
pout.close();
}
closeQuietly(socket);
}
}
public static boolean isPrimaryAnimationServerRunning(String ip, int port) {
Socket socket = null;
PrintWriter pout = null;
try {
System.out.println(TAG + " - Connecting with primary server " + ip + ":" + port);
socket = new Socket(ip, port);
pout = new PrintWriter(socket.getOutputStream(), true);
pout.print(AnimationMsg.PING);
return true;
} catch (Exception e) {
System.err.println("Could not connect to animation server: " + ip + ":"
+ port + ": " + e);
} finally {
if (pout != null) {
pout.close();
}
closeQuietly(socket);
}
return false;
}
/**
* Validate ip address with regular expression
* @param ip ip address for validation
* @return true valid ip address, false invalid ip address
*/
public static boolean validateIpAddress(final String ip){
Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
return pattern.matcher(ip).matches();
}
public static String getVmIpLinux() {
String localIpAddress = "";
Enumeration<NetworkInterface> e;
try {
e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration<InetAddress> ee = n.getInetAddresses();
boolean stop = false;
while (ee.hasMoreElements()) {
InetAddress i = (InetAddress) ee.nextElement();
if (i.getHostAddress().startsWith("10.0.")) {
localIpAddress = i.getHostAddress();
stop = true;
break;
}
}
if (stop)
break;
}
} catch (SocketException e1) {
System.err.println("Error while getting VM IP: " + e1);
}
return localIpAddress;
}
/**
* Connects to the DS and returns the IP of the demo animation server.
* @param dsIp
* @param dsPort
* @return IP of the demo animation server or null.
*/
public static String getDemoAnimationServerIpFromDs(String dsIp, int dsPort) {
String ip = null;
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
socket = new Socket(dsIp, dsPort);
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
oos.writeByte(RapidMessages.GET_DEMO_SERVER_IP_DS);
oos.flush();
ip = ois.readUTF();
}catch (IOException e) {
System.err.println("Could not connect to DS for getting demo server IP: " + e);
} finally {
closeQuietly(ois);
closeQuietly(oos);
closeQuietly(socket);
}
return ip;
}
}
| removed the following comments so that the screenshots are not
confusing: "Could not connect to animation server: 83.235.169.221:6666:
java.net.ConnectException: Connection refused" | src/eu/project/rapid/common/RapidUtils.java | removed the following comments so that the screenshots are not confusing: "Could not connect to animation server: 83.235.169.221:6666: java.net.ConnectException: Connection refused" | <ide><path>rc/eu/project/rapid/common/RapidUtils.java
<ide> pout.print(msg);
<ide>
<ide> } catch (Exception e) {
<del> System.err.println("Could not connect to animation server: " + demoServerIp + ":"
<del> + demoServerPort + ": " + e);
<add>// System.err.println("Could not connect to animation server: " + demoServerIp + ":"
<add>// + demoServerPort + ": " + e);
<ide> } finally {
<ide> if (pout != null) {
<ide> pout.close();
<ide> pout.print(AnimationMsg.PING);
<ide> return true;
<ide> } catch (Exception e) {
<del> System.err.println("Could not connect to animation server: " + ip + ":"
<del> + port + ": " + e);
<add>// System.err.println("Could not connect to animation server: " + ip + ":"
<add>// + port + ": " + e);
<ide> } finally {
<ide> if (pout != null) {
<ide> pout.close(); |
|
Java | bsd-2-clause | 41019fbee28bcaec19eb0f3cba8c19b1a9790664 | 0 | wrld3d/wrld-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app | // Copyright eeGeo Ltd (2012-2015), All Rights Reserved
package com.eegeo.mobileexampleapp;
import java.io.IOException;
import java.io.InputStream;
import org.json.JSONException;
import org.json.JSONObject;
import com.eegeo.entrypointinfrastructure.EegeoSurfaceView;
import com.eegeo.entrypointinfrastructure.MainActivity;
import com.eegeo.entrypointinfrastructure.NativeJniCalls;
import com.eegeo.mobileexampleapp.R;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.Constants;
import net.hockeyapp.android.CrashManagerListener;
import net.hockeyapp.android.NativeCrashManager;
public class BackgroundThreadActivity extends MainActivity
{
private EegeoSurfaceView m_surfaceView;
private SurfaceHolder m_surfaceHolder;
private long m_nativeAppWindowPtr;
private ThreadedUpdateRunner m_threadedRunner;
private Thread m_updater;
private String m_hockeyAppId;
/* The url used if the app is opened by a deep link.
* As the app in singleTask this is set in onNewIntent and must be
* set to null before for the app pauses.
*/
private Uri m_deepLinkUrlData;
static
{
System.loadLibrary("eegeo-mobile-example-app");
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0)
{
finish();
return;
}
m_hockeyAppId = readHockeyAppId();
Constants.loadFromContext(this);
NativeJniCalls.setUpBreakpad(Constants.FILES_PATH);
NativeCrashManager.handleDumpFiles(this, m_hockeyAppId);
PackageInfo pInfo = null;
try
{
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
}
catch (NameNotFoundException e)
{
e.printStackTrace();
}
final String versionName = pInfo.versionName;
final int versionCode = pInfo.versionCode;
setDisplayOrientationBasedOnDeviceProperties();
setContentView(R.layout.activity_main);
Intent intent = getIntent();
if(intent !=null)
{
m_deepLinkUrlData = intent.getData();
}
m_surfaceView = (EegeoSurfaceView)findViewById(R.id.surface);
m_surfaceView.getHolder().addCallback(this);
m_surfaceView.setActivity(this);
DisplayMetrics dm = getResources().getDisplayMetrics();
final float dpi = dm.ydpi;
final int density = dm.densityDpi;
final Activity activity = this;
m_threadedRunner = new ThreadedUpdateRunner(false);
m_updater = new Thread(m_threadedRunner);
m_updater.start();
m_threadedRunner.blockUntilThreadStartedRunning();
runOnNativeThread(new Runnable()
{
public void run()
{
m_nativeAppWindowPtr = NativeJniCalls.createNativeCode(activity, getAssets(), dpi, density, versionName, versionCode);
if(m_nativeAppWindowPtr == 0)
{
throw new RuntimeException("Failed to start native code.");
}
}
});
}
public void runOnNativeThread(Runnable runnable)
{
m_threadedRunner.postTo(runnable);
}
@Override
protected void onResume()
{
super.onResume();
if(hasValidHockeyAppId())
{
registerCrashLogging();
}
runOnNativeThread(new Runnable()
{
public void run()
{
NativeJniCalls.resumeNativeCode();
m_threadedRunner.start();
if(m_surfaceHolder != null && m_surfaceHolder.getSurface() != null)
{
NativeJniCalls.setNativeSurface(m_surfaceHolder.getSurface());
if(m_deepLinkUrlData != null)
{
NativeJniCalls.handleUrlOpenEvent(m_deepLinkUrlData.getHost(), m_deepLinkUrlData.getPath());
m_deepLinkUrlData = null;
}
}
}
});
}
@Override
protected void onPause()
{
super.onPause();
runOnNativeThread(new Runnable()
{
public void run()
{
m_threadedRunner.stop();
NativeJniCalls.pauseNativeCode();
}
});
}
@Override
protected void onDestroy()
{
super.onDestroy();
if (m_threadedRunner == null)
{
return;
}
runOnNativeThread(new Runnable()
{
public void run()
{
NativeJniCalls.stopUpdatingNativeCode();
m_threadedRunner.flagUpdatingNativeCodeStopped();
}
});
m_threadedRunner.blockUntilThreadHasStoppedUpdatingPlatform();
NativeJniCalls.destroyApplicationUi();
runOnNativeThread(new Runnable()
{
public void run()
{
m_threadedRunner.stop();
NativeJniCalls.destroyNativeCode();
m_threadedRunner.destroyed();
}
});
m_threadedRunner.blockUntilThreadHasDestroyedPlatform();
m_nativeAppWindowPtr = 0;
}
@Override
public void onBackPressed()
{
moveTaskToBack(true);
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
//nothing to do
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
runOnNativeThread(new Runnable()
{
public void run()
{
m_threadedRunner.stop();
}
});
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
final SurfaceHolder h = holder;
runOnNativeThread(new Runnable()
{
public void run()
{
m_surfaceHolder = h;
if(m_surfaceHolder != null)
{
NativeJniCalls.setNativeSurface(m_surfaceHolder.getSurface());
m_threadedRunner.start();
if(m_deepLinkUrlData != null)
{
NativeJniCalls.handleUrlOpenEvent(m_deepLinkUrlData.getHost(), m_deepLinkUrlData.getPath());
m_deepLinkUrlData = null;
}
}
}
});
}
@Override
public void onNewIntent(Intent intent) {
m_deepLinkUrlData = intent.getData();
}
public void dispatchRevealUiMessageToUiThreadFromNativeThread(final long nativeCallerPointer)
{
runOnUiThread(new Runnable()
{
public void run()
{
NativeJniCalls.revealApplicationUi(nativeCallerPointer);
}
});
}
public void dispatchUiCreatedMessageToNativeThreadFromUiThread(final long nativeCallerPointer)
{
runOnNativeThread(new Runnable()
{
public void run()
{
NativeJniCalls.handleApplicationUiCreatedOnNativeThread(nativeCallerPointer);
}
});
}
private void setDisplayOrientationBasedOnDeviceProperties()
{
// Technique based on http://stackoverflow.com/a/9308284 using res/values configuration.
if(getResources().getBoolean(R.bool.isPhone))
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}
}
private String readHockeyAppId()
{
try
{
String applicationConfigurationPath = NativeJniCalls.getAppConfigurationPath();
InputStream is = getAssets().open(applicationConfigurationPath);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String jsonStr = new String(buffer, "UTF-8");
JSONObject json = new JSONObject(jsonStr);
return json.get("hockey_app_id").toString();
} catch (IOException e) {
// Master Ball
} catch (JSONException e) {
// Master Ball
}
return "";
}
private boolean hasValidHockeyAppId()
{
return m_hockeyAppId.length() == 32;
}
private void registerCrashLogging()
{
CrashManager.register(this, m_hockeyAppId, new CrashManagerListener() {
public boolean shouldAutoUploadCrashes() {
return true;
}
});
}
private class ThreadedUpdateRunner implements Runnable
{
private long m_endOfLastFrameNano;
private boolean m_running;
private Handler m_nativeThreadHandler;
private float m_frameThrottleDelaySeconds;
private boolean m_destroyed;
private boolean m_stoppedUpdatingPlatformBeforeTeardown;
public ThreadedUpdateRunner(boolean running)
{
m_endOfLastFrameNano = System.nanoTime();
m_running = false;
m_destroyed = false;
m_stoppedUpdatingPlatformBeforeTeardown = false;
float targetFramesPerSecond = 30.f;
m_frameThrottleDelaySeconds = 1.f/targetFramesPerSecond;
}
synchronized void blockUntilThreadStartedRunning()
{
while(m_nativeThreadHandler == null);
}
synchronized void blockUntilThreadHasDestroyedPlatform()
{
while(!m_destroyed);
}
synchronized void blockUntilThreadHasStoppedUpdatingPlatform()
{
while(!m_stoppedUpdatingPlatformBeforeTeardown);
}
public void postTo(Runnable runnable)
{
m_nativeThreadHandler.post(runnable);
}
public void start()
{
m_running = true;
}
public void stop()
{
m_running = false;
}
public void destroyed()
{
m_destroyed = true;
}
void flagUpdatingNativeCodeStopped()
{
m_stoppedUpdatingPlatformBeforeTeardown = true;
}
public void run()
{
Looper.prepare();
m_nativeThreadHandler = new Handler();
runOnNativeThread(new Runnable()
{
public void run()
{
long timeNowNano = System.nanoTime();
long nanoDelta = timeNowNano - m_endOfLastFrameNano;
final float deltaSeconds = (float)((double)nanoDelta / 1e9);
if(deltaSeconds > m_frameThrottleDelaySeconds)
{
if(m_running)
{
NativeJniCalls.updateNativeCode(deltaSeconds);
runOnUiThread(new Runnable()
{
public void run()
{
NativeJniCalls.updateUiViewCode(deltaSeconds);
}
});
}
else
{
SystemClock.sleep(200);
}
m_endOfLastFrameNano = timeNowNano;
}
runOnNativeThread(this);
}
});
Looper.loop();
}
}
}
| android/src/com/eegeo/mobileexampleapp/BackgroundThreadActivity.java | // Copyright eeGeo Ltd (2012-2015), All Rights Reserved
package com.eegeo.mobileexampleapp;
import java.io.IOException;
import java.io.InputStream;
import org.json.JSONException;
import org.json.JSONObject;
import com.eegeo.entrypointinfrastructure.EegeoSurfaceView;
import com.eegeo.entrypointinfrastructure.MainActivity;
import com.eegeo.entrypointinfrastructure.NativeJniCalls;
import com.eegeo.mobileexampleapp.R;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.Constants;
import net.hockeyapp.android.CrashManagerListener;
import net.hockeyapp.android.NativeCrashManager;
public class BackgroundThreadActivity extends MainActivity
{
private EegeoSurfaceView m_surfaceView;
private SurfaceHolder m_surfaceHolder;
private long m_nativeAppWindowPtr;
private ThreadedUpdateRunner m_threadedRunner;
private Thread m_updater;
private String m_hockeyAppId;
/* The url used if the app is opened by a deep link.
* As the app in singleTask this is set in onNewIntent and must be
* set to null before for the app pauses.
*/
private Uri m_deepLinkUrlData;
static
{
System.loadLibrary("eegeo-mobile-example-app");
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0)
{
finish();
return;
}
m_hockeyAppId = readHockeyAppId();
Constants.loadFromContext(this);
NativeJniCalls.setUpBreakpad(Constants.FILES_PATH);
NativeCrashManager.handleDumpFiles(this, m_hockeyAppId);
PackageInfo pInfo = null;
try
{
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
}
catch (NameNotFoundException e)
{
e.printStackTrace();
}
final String versionName = pInfo.versionName;
final int versionCode = pInfo.versionCode;
setDisplayOrientationBasedOnDeviceProperties();
setContentView(R.layout.activity_main);
Intent intent = getIntent();
if(intent !=null)
{
m_deepLinkUrlData = intent.getData();
}
m_surfaceView = (EegeoSurfaceView)findViewById(R.id.surface);
m_surfaceView.getHolder().addCallback(this);
m_surfaceView.setActivity(this);
DisplayMetrics dm = getResources().getDisplayMetrics();
final float dpi = dm.ydpi;
final int density = dm.densityDpi;
final Activity activity = this;
m_threadedRunner = new ThreadedUpdateRunner(false);
m_updater = new Thread(m_threadedRunner);
m_updater.start();
m_threadedRunner.blockUntilThreadStartedRunning();
runOnNativeThread(new Runnable()
{
public void run()
{
m_nativeAppWindowPtr = NativeJniCalls.createNativeCode(activity, getAssets(), dpi, density, versionName, versionCode);
if(m_nativeAppWindowPtr == 0)
{
throw new RuntimeException("Failed to start native code.");
}
}
});
}
public void runOnNativeThread(Runnable runnable)
{
m_threadedRunner.postTo(runnable);
}
@Override
protected void onResume()
{
super.onResume();
registerCrashLogging();
runOnNativeThread(new Runnable()
{
public void run()
{
NativeJniCalls.resumeNativeCode();
m_threadedRunner.start();
if(m_surfaceHolder != null && m_surfaceHolder.getSurface() != null)
{
NativeJniCalls.setNativeSurface(m_surfaceHolder.getSurface());
if(m_deepLinkUrlData != null)
{
NativeJniCalls.handleUrlOpenEvent(m_deepLinkUrlData.getHost(), m_deepLinkUrlData.getPath());
m_deepLinkUrlData = null;
}
}
}
});
}
@Override
protected void onPause()
{
super.onPause();
runOnNativeThread(new Runnable()
{
public void run()
{
m_threadedRunner.stop();
NativeJniCalls.pauseNativeCode();
}
});
}
@Override
protected void onDestroy()
{
super.onDestroy();
if (m_threadedRunner == null)
{
return;
}
runOnNativeThread(new Runnable()
{
public void run()
{
NativeJniCalls.stopUpdatingNativeCode();
m_threadedRunner.flagUpdatingNativeCodeStopped();
}
});
m_threadedRunner.blockUntilThreadHasStoppedUpdatingPlatform();
NativeJniCalls.destroyApplicationUi();
runOnNativeThread(new Runnable()
{
public void run()
{
m_threadedRunner.stop();
NativeJniCalls.destroyNativeCode();
m_threadedRunner.destroyed();
}
});
m_threadedRunner.blockUntilThreadHasDestroyedPlatform();
m_nativeAppWindowPtr = 0;
}
@Override
public void onBackPressed()
{
moveTaskToBack(true);
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
//nothing to do
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
runOnNativeThread(new Runnable()
{
public void run()
{
m_threadedRunner.stop();
}
});
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
final SurfaceHolder h = holder;
runOnNativeThread(new Runnable()
{
public void run()
{
m_surfaceHolder = h;
if(m_surfaceHolder != null)
{
NativeJniCalls.setNativeSurface(m_surfaceHolder.getSurface());
m_threadedRunner.start();
if(m_deepLinkUrlData != null)
{
NativeJniCalls.handleUrlOpenEvent(m_deepLinkUrlData.getHost(), m_deepLinkUrlData.getPath());
m_deepLinkUrlData = null;
}
}
}
});
}
@Override
public void onNewIntent(Intent intent) {
m_deepLinkUrlData = intent.getData();
}
public void dispatchRevealUiMessageToUiThreadFromNativeThread(final long nativeCallerPointer)
{
runOnUiThread(new Runnable()
{
public void run()
{
NativeJniCalls.revealApplicationUi(nativeCallerPointer);
}
});
}
public void dispatchUiCreatedMessageToNativeThreadFromUiThread(final long nativeCallerPointer)
{
runOnNativeThread(new Runnable()
{
public void run()
{
NativeJniCalls.handleApplicationUiCreatedOnNativeThread(nativeCallerPointer);
}
});
}
private void setDisplayOrientationBasedOnDeviceProperties()
{
// Technique based on http://stackoverflow.com/a/9308284 using res/values configuration.
if(getResources().getBoolean(R.bool.isPhone))
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}
}
private String readHockeyAppId()
{
try
{
String applicationConfigurationPath = NativeJniCalls.getAppConfigurationPath();
InputStream is = getAssets().open(applicationConfigurationPath);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String jsonStr = new String(buffer, "UTF-8");
JSONObject json = new JSONObject(jsonStr);
return json.get("hockey_app_id").toString();
} catch (IOException e) {
// Master Ball
} catch (JSONException e) {
// Master Ball
}
return "";
}
private void registerCrashLogging()
{
CrashManager.register(this, m_hockeyAppId, new CrashManagerListener() {
public boolean shouldAutoUploadCrashes() {
return true;
}
});
}
private class ThreadedUpdateRunner implements Runnable
{
private long m_endOfLastFrameNano;
private boolean m_running;
private Handler m_nativeThreadHandler;
private float m_frameThrottleDelaySeconds;
private boolean m_destroyed;
private boolean m_stoppedUpdatingPlatformBeforeTeardown;
public ThreadedUpdateRunner(boolean running)
{
m_endOfLastFrameNano = System.nanoTime();
m_running = false;
m_destroyed = false;
m_stoppedUpdatingPlatformBeforeTeardown = false;
float targetFramesPerSecond = 30.f;
m_frameThrottleDelaySeconds = 1.f/targetFramesPerSecond;
}
synchronized void blockUntilThreadStartedRunning()
{
while(m_nativeThreadHandler == null);
}
synchronized void blockUntilThreadHasDestroyedPlatform()
{
while(!m_destroyed);
}
synchronized void blockUntilThreadHasStoppedUpdatingPlatform()
{
while(!m_stoppedUpdatingPlatformBeforeTeardown);
}
public void postTo(Runnable runnable)
{
m_nativeThreadHandler.post(runnable);
}
public void start()
{
m_running = true;
}
public void stop()
{
m_running = false;
}
public void destroyed()
{
m_destroyed = true;
}
void flagUpdatingNativeCodeStopped()
{
m_stoppedUpdatingPlatformBeforeTeardown = true;
}
public void run()
{
Looper.prepare();
m_nativeThreadHandler = new Handler();
runOnNativeThread(new Runnable()
{
public void run()
{
long timeNowNano = System.nanoTime();
long nanoDelta = timeNowNano - m_endOfLastFrameNano;
final float deltaSeconds = (float)((double)nanoDelta / 1e9);
if(deltaSeconds > m_frameThrottleDelaySeconds)
{
if(m_running)
{
NativeJniCalls.updateNativeCode(deltaSeconds);
runOnUiThread(new Runnable()
{
public void run()
{
NativeJniCalls.updateUiViewCode(deltaSeconds);
}
});
}
else
{
SystemClock.sleep(200);
}
m_endOfLastFrameNano = timeNowNano;
}
runOnNativeThread(this);
}
});
Looper.loop();
}
}
}
| Now only registering crash logging when a hockey app id of valid length is supplied. Buddy: Jonty
| android/src/com/eegeo/mobileexampleapp/BackgroundThreadActivity.java | Now only registering crash logging when a hockey app id of valid length is supplied. Buddy: Jonty | <ide><path>ndroid/src/com/eegeo/mobileexampleapp/BackgroundThreadActivity.java
<ide> protected void onResume()
<ide> {
<ide> super.onResume();
<del> registerCrashLogging();
<add> if(hasValidHockeyAppId())
<add> {
<add> registerCrashLogging();
<add> }
<ide>
<ide> runOnNativeThread(new Runnable()
<ide> {
<ide> return "";
<ide> }
<ide>
<add> private boolean hasValidHockeyAppId()
<add> {
<add> return m_hockeyAppId.length() == 32;
<add> }
<ide> private void registerCrashLogging()
<ide> {
<ide> CrashManager.register(this, m_hockeyAppId, new CrashManagerListener() { |
|
Java | apache-2.0 | b69775b591a94ab809fc699290888cbe9418c150 | 0 | korpling/ANNIS,korpling/ANNIS,korpling/ANNIS,korpling/ANNIS,korpling/ANNIS | /*
* Copyright 2011 Corpuslinguistic working group Humboldt University Berlin.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package annis.gui.querybuilder;
import annis.gui.QueryController;
import annis.gui.widgets.GripDragComponent;
import annis.gui.widgets.SimpleCanvas;
import annis.libgui.Helper;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.vaadin.event.dd.DragAndDropEvent;
import com.vaadin.event.dd.DropHandler;
import com.vaadin.event.dd.acceptcriteria.AcceptAll;
import com.vaadin.event.dd.acceptcriteria.AcceptCriterion;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.AbsoluteLayout.ComponentPosition;
import com.vaadin.ui.DragAndDropWrapper;
import com.vaadin.ui.DragAndDropWrapper.WrapperTargetDetails;
import com.vaadin.ui.Layout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.corpus_tools.annis.ApiException;
import org.corpus_tools.annis.api.CorporaApi;
import org.corpus_tools.annis.api.model.Annotation;
import org.slf4j.LoggerFactory;
/**
*
* @author thomas
*/
public class TigerQueryBuilderCanvas extends Panel {
private static class AbsoluteDropHandler implements DropHandler {
/**
*
*/
private static final long serialVersionUID = 8456460938439624526L;
private AbsoluteLayout layout;
private TigerQueryBuilderCanvas parent;
public AbsoluteDropHandler(TigerQueryBuilderCanvas parent, AbsoluteLayout layout) {
this.layout = layout;
this.parent = parent;
}
@Override
public void drop(DragAndDropEvent event) {
GripDragComponent.MouseEventTransferable t =
(GripDragComponent.MouseEventTransferable) event.getTransferable();
WrapperTargetDetails details = (WrapperTargetDetails) event.getTargetDetails();
if (t == null || details == null) {
return;
}
int xChange = details.getMouseEvent().getClientX() - t.getClientX();
int yChange = details.getMouseEvent().getClientY() - t.getClientY();
// Move the component in the absolute layout
ComponentPosition pos = layout.getPosition(t.getSourceComponent().getParent());
pos.setLeftValue(pos.getLeftValue() + xChange);
pos.setTopValue(pos.getTopValue() + yChange);
if (parent != null) {
parent.updateLinesAndEdgePositions();
parent.requestRepaint();
}
}
@Override
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
}
/**
*
*/
private static final long serialVersionUID = 4564976366028699909L;
private static final org.slf4j.Logger log =
LoggerFactory.getLogger(TigerQueryBuilderCanvas.class);
private SimpleCanvas canvas;
private Map<NodeWindow, GripDragComponent> nodes;
private List<EdgeWindow> edges;
private AbsoluteLayout area;
private AbsoluteDropHandler handler;
private int number = 0;
private NodeWindow preparedEdgeSource = null;
private final QueryController controller;
public TigerQueryBuilderCanvas(QueryController controller) {
this.controller = controller;
nodes = new HashMap<>();
edges = new ArrayList<>();
setSizeFull();
area = new AbsoluteLayout();
area.setWidth("2000px");
area.setHeight("2000px");
area.addStyleName("no-vertical-drag-hints");
area.addStyleName("no-horizontal-drag-hints");
area.addStyleName("no-box-drag-hints");
canvas = new SimpleCanvas();
canvas.setSizeFull();
canvas.addStyleName("tigerquery-builder-canvas");
handler = new AbsoluteDropHandler(this, area);
DragAndDropWrapper areaPane = new DragAndDropWrapper(area);
areaPane.setWidth("2000px");
areaPane.setHeight("2000px");
areaPane.setDropHandler(handler);
area.addComponent(canvas, "top:0px;left:0px");
setContent(areaPane);
addStyleName("no-vertical-drag-hints");
addStyleName("no-horizontal-drag-hints");
addStyleName("no-box-drag-hints");
}
public void addEdge(NodeWindow target) {
for (NodeWindow w : nodes.keySet()) {
w.setPrepareEdgeDock(false);
}
if (preparedEdgeSource != target) {
boolean valid = true;
for (EdgeWindow e : edges) {
if (e.getSource() == preparedEdgeSource && e.getTarget() == target) {
valid = false;
break;
}
}
if (valid) {
EdgeWindow e = new EdgeWindow(this, preparedEdgeSource, target);
e.setWidth("170px");
e.setHeight("80px");
e.addStyleName("tigerquery-builder-overlay");
edges.add(e);
area.addComponent(e);
updateLinesAndEdgePositions();
updateQuery();
} else {
Notification.show("There is already such an edge", Notification.Type.WARNING_MESSAGE);
}
}
}
public void addNode() {
final NodeWindow n = new NodeWindow(number++, this);
GripDragComponent panel = new GripDragComponent(n);
panel.setWidth(NodeWindow.WIDTH, Layout.Unit.PIXELS);
panel.setHeight(NodeWindow.HEIGHT, Layout.Unit.PIXELS);
nodes.put(n, panel);
area.addComponent(panel,
"top:" + (10 + ((NodeWindow.HEIGHT + 20) * (number - 1))) + "px;left:10px");
// area.addComponent(wrapper, "top:" + (10 + (120 * (number-1))) +
// "px;left:10px");
updateQuery();
}
public void clearAll() {
for (EdgeWindow w : edges) {
area.removeComponent(w);
}
edges.clear();
for (GripDragComponent w : nodes.values()) {
area.removeComponent(w);
}
nodes.clear();
number = 0;
updateLinesAndEdgePositions();
updateQuery();
}
private List<Line2D> createArrow(double x, double y, double direction, double arrowLength) {
LinkedList<Line2D> result = new LinkedList<>();
double dir1 = direction + Math.PI / 8.0;
double dir2 = direction - Math.PI / 8.0;
double end1_x = x - arrowLength * Math.cos(dir1);
double end1_y = y - arrowLength * Math.sin(dir1);
double end2_x = x - arrowLength * Math.cos(dir2);
double end2_y = y - arrowLength * Math.sin(dir2);
result.add(new Line2D.Double(x, y, end1_x, end1_y));
result.add(new Line2D.Double(x, y, end2_x, end2_y));
return result;
}
public void deleteEdge(EdgeWindow e) {
area.removeComponent(e);
edges.remove(e);
updateLinesAndEdgePositions();
updateQuery();
}
public void deleteNode(NodeWindow n) {
LinkedList<EdgeWindow> edgesToRemove = new LinkedList<>();
for (EdgeWindow e : edges) {
if (e.getSource() == n || e.getTarget() == n) {
edgesToRemove.add(e);
area.removeComponent(e);
}
}
edges.removeAll(edgesToRemove);
area.removeComponent(nodes.get(n));
nodes.remove(n);
updateLinesAndEdgePositions();
updateQuery();
}
public String getAQLQuery() {
StringBuilder query = new StringBuilder();
StringBuffer nodeIdentityOperations = new StringBuffer();
Map<NodeWindow, Integer> nodeComponentMap = new HashMap<>();
// creating node definitions
int componentCount = 0;
for (NodeWindow nodeWindow : nodes.keySet()) {
List<NodeWindow.ConstraintLayout> constraints = nodeWindow.getConstraints();
if (componentCount++ > 0) {
query.append(" & ");
}
if (constraints.size() > 0) {
int nodeComponentCount = 0;
for (NodeWindow.ConstraintLayout c : constraints) {
if (nodeComponentCount++ > 0) {
nodeIdentityOperations.append("\n& #").append(componentCount).append(" _=_ #")
.append(componentCount + 1);
query.append(" & ");
componentCount++;
}
String operator = c.getOperator().replace("~", "=");
String quotes = c.getOperator().equals("=") || c.getOperator().equals("!=") ? "\"" : "/";
String prefix = "";
if (c.getName().trim().isEmpty() || c.getName().trim().equals("tok")) {
if (operator.equals("!=")) {
if (c.getName().trim().isEmpty()) {
prefix = "tok" + c.getName() + operator;
} else {
prefix = c.getName() + operator;
}
}
} else {
prefix = c.getName() + operator;
}
if ("".equals(c.getValue())) {
query.append(c.getName());
} else {
query.append(prefix).append(quotes).append(c.getValue()).append(quotes);
}
}
} else {
query.append("node");
}
nodeComponentMap.put(nodeWindow, componentCount);
}
query.append(nodeIdentityOperations);
// appending node relations
for (EdgeWindow edgeWindow : edges) {
query.append("\n& ");
query.append('#').append(nodeComponentMap.get(edgeWindow.getSource())).append(" ")
.append(edgeWindow.getOperator()).append(" ").append("#")
.append(nodeComponentMap.get(edgeWindow.getTarget()));
}
return query.toString();
}
public Set<String> getAvailableAnnotationNames() {
Set<String> result = new TreeSet<>();
CorporaApi api = new CorporaApi(Helper.getClient(UI.getCurrent()));
// get current corpus selection
Collection<String> corpusSelection = controller.getState().getSelectedCorpora();
if (corpusSelection != null) {
try {
for (String corpus : corpusSelection) {
try {
for (Annotation anno : api.corpusNodeAnnotations(corpus, false, true)) {
result.add(anno.getKey().getName());
}
} catch (ApiException ex) {
log.error("Could not get node annotations for corpus " + corpus, ex);
}
}
} catch (UniformInterfaceException | ClientHandlerException ex) {
log.error(null, ex);
}
}
return result;
}
public void prepareAddingEdge(NodeWindow sourceNode) {
preparedEdgeSource = sourceNode;
for (NodeWindow w : nodes.keySet()) {
if (w != sourceNode) {
w.setPrepareEdgeDock(true);
}
}
}
public void updateLinesAndEdgePositions() {
canvas.getLines().clear();
for (EdgeWindow e : edges) {
GripDragComponent w1 = nodes.get(e.getSource());
GripDragComponent w2 = nodes.get(e.getTarget());
ComponentPosition p1 = area.getPosition(w1);
ComponentPosition p2 = area.getPosition(w2);
float x1 = p1.getLeftValue() + (w1.getWidth() / 2);
float y1 = p1.getTopValue() + (w1.getHeight() / 2);
float x2 = p2.getLeftValue() + (w2.getWidth() / 2);
float y2 = p2.getTopValue() + (w2.getHeight() / 2);
float v_x = x2 - x1;
float v_y = y2 - y1;
// add line
canvas.getLines().add(new Line2D.Float(x1, y1, x2, y2));
// set position on half of the line for the edge window
ComponentPosition posEdge = area.getPosition(e);
float vectorLength = (float) Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
float xM = x1 + (vectorLength / 2.0f) * ((x2 - x1) / vectorLength);
float yM = y1 + (vectorLength / 2.0f) * ((y2 - y1) / vectorLength);
double normV_x = v_x / vectorLength;
double normV_y = v_y / vectorLength;
double pos1_x = (2.1 * vectorLength / 3) * normV_x + x1;
double pos1_y = (2.1 * vectorLength / 3) * normV_y + y1;
double origDir = Math.atan2(normV_y, normV_x);
double pos2_x = ((1 * vectorLength) / 3) * normV_x + x1;
double pos2_y = ((1 * vectorLength) / 3) * normV_y + y1;
canvas.getLines().addAll(createArrow(pos1_x, pos1_y, origDir, 20.0));
canvas.getLines().addAll(createArrow(pos2_x, pos2_y, origDir, 20.0));
posEdge.setLeftValue(xM - e.getWidth() / 2.0f);
posEdge.setTopValue(yM - e.getHeight() / 2.0f);
}
canvas.markAsDirty();
}
public void updateQuery() {
controller.getState().getAql().setValue(getAQLQuery());
}
}
| annis-gui/src/main/java/annis/gui/querybuilder/TigerQueryBuilderCanvas.java | /*
* Copyright 2011 Corpuslinguistic working group Humboldt University Berlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package annis.gui.querybuilder;
import annis.gui.QueryController;
import annis.gui.widgets.GripDragComponent;
import annis.gui.widgets.SimpleCanvas;
import annis.libgui.Helper;
import annis.service.objects.AnnisAttribute;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.vaadin.event.dd.DragAndDropEvent;
import com.vaadin.event.dd.DropHandler;
import com.vaadin.event.dd.acceptcriteria.AcceptAll;
import com.vaadin.event.dd.acceptcriteria.AcceptCriterion;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.AbsoluteLayout.ComponentPosition;
import com.vaadin.ui.DragAndDropWrapper;
import com.vaadin.ui.DragAndDropWrapper.WrapperTargetDetails;
import com.vaadin.ui.Layout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.LoggerFactory;
/**
*
* @author thomas
*/
public class TigerQueryBuilderCanvas extends Panel {
private static class AbsoluteDropHandler implements DropHandler {
/**
*
*/
private static final long serialVersionUID = 8456460938439624526L;
private AbsoluteLayout layout;
private TigerQueryBuilderCanvas parent;
public AbsoluteDropHandler(TigerQueryBuilderCanvas parent, AbsoluteLayout layout) {
this.layout = layout;
this.parent = parent;
}
@Override
public void drop(DragAndDropEvent event) {
GripDragComponent.MouseEventTransferable t = (GripDragComponent.MouseEventTransferable) event
.getTransferable();
WrapperTargetDetails details = (WrapperTargetDetails) event.getTargetDetails();
if (t == null || details == null) {
return;
}
int xChange = details.getMouseEvent().getClientX() - t.getClientX();
int yChange = details.getMouseEvent().getClientY() - t.getClientY();
// Move the component in the absolute layout
ComponentPosition pos = layout.getPosition(t.getSourceComponent().getParent());
pos.setLeftValue(pos.getLeftValue() + xChange);
pos.setTopValue(pos.getTopValue() + yChange);
if (parent != null) {
parent.updateLinesAndEdgePositions();
parent.requestRepaint();
}
}
@Override
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
}
private static class AnnisAttributeListType extends GenericType<List<AnnisAttribute>> {
public AnnisAttributeListType() {}
}
/**
*
*/
private static final long serialVersionUID = 4564976366028699909L;
private static final org.slf4j.Logger log = LoggerFactory.getLogger(TigerQueryBuilderCanvas.class);
private SimpleCanvas canvas;
private Map<NodeWindow, GripDragComponent> nodes;
private List<EdgeWindow> edges;
private AbsoluteLayout area;
private AbsoluteDropHandler handler;
private int number = 0;
private NodeWindow preparedEdgeSource = null;
private final QueryController controller;
public TigerQueryBuilderCanvas(QueryController controller) {
this.controller = controller;
nodes = new HashMap<>();
edges = new ArrayList<>();
setSizeFull();
area = new AbsoluteLayout();
area.setWidth("2000px");
area.setHeight("2000px");
area.addStyleName("no-vertical-drag-hints");
area.addStyleName("no-horizontal-drag-hints");
area.addStyleName("no-box-drag-hints");
canvas = new SimpleCanvas();
canvas.setSizeFull();
canvas.addStyleName("tigerquery-builder-canvas");
handler = new AbsoluteDropHandler(this, area);
DragAndDropWrapper areaPane = new DragAndDropWrapper(area);
areaPane.setWidth("2000px");
areaPane.setHeight("2000px");
areaPane.setDropHandler(handler);
area.addComponent(canvas, "top:0px;left:0px");
setContent(areaPane);
addStyleName("no-vertical-drag-hints");
addStyleName("no-horizontal-drag-hints");
addStyleName("no-box-drag-hints");
}
public void addEdge(NodeWindow target) {
for (NodeWindow w : nodes.keySet()) {
w.setPrepareEdgeDock(false);
}
if (preparedEdgeSource != target) {
boolean valid = true;
for (EdgeWindow e : edges) {
if (e.getSource() == preparedEdgeSource && e.getTarget() == target) {
valid = false;
break;
}
}
if (valid) {
EdgeWindow e = new EdgeWindow(this, preparedEdgeSource, target);
e.setWidth("170px");
e.setHeight("80px");
e.addStyleName("tigerquery-builder-overlay");
edges.add(e);
area.addComponent(e);
updateLinesAndEdgePositions();
updateQuery();
} else {
Notification.show("There is already such an edge", Notification.Type.WARNING_MESSAGE);
}
}
}
public void addNode() {
final NodeWindow n = new NodeWindow(number++, this);
GripDragComponent panel = new GripDragComponent(n);
panel.setWidth(NodeWindow.WIDTH, Layout.Unit.PIXELS);
panel.setHeight(NodeWindow.HEIGHT, Layout.Unit.PIXELS);
nodes.put(n, panel);
area.addComponent(panel, "top:" + (10 + ((NodeWindow.HEIGHT + 20) * (number - 1))) + "px;left:10px");
// area.addComponent(wrapper, "top:" + (10 + (120 * (number-1))) +
// "px;left:10px");
updateQuery();
}
public void clearAll() {
for (EdgeWindow w : edges) {
area.removeComponent(w);
}
edges.clear();
for (GripDragComponent w : nodes.values()) {
area.removeComponent(w);
}
nodes.clear();
number = 0;
updateLinesAndEdgePositions();
updateQuery();
}
private List<Line2D> createArrow(double x, double y, double direction, double arrowLength) {
LinkedList<Line2D> result = new LinkedList<>();
double dir1 = direction + Math.PI / 8.0;
double dir2 = direction - Math.PI / 8.0;
double end1_x = x - arrowLength * Math.cos(dir1);
double end1_y = y - arrowLength * Math.sin(dir1);
double end2_x = x - arrowLength * Math.cos(dir2);
double end2_y = y - arrowLength * Math.sin(dir2);
result.add(new Line2D.Double(x, y, end1_x, end1_y));
result.add(new Line2D.Double(x, y, end2_x, end2_y));
return result;
}
public void deleteEdge(EdgeWindow e) {
area.removeComponent(e);
edges.remove(e);
updateLinesAndEdgePositions();
updateQuery();
}
public void deleteNode(NodeWindow n) {
LinkedList<EdgeWindow> edgesToRemove = new LinkedList<>();
for (EdgeWindow e : edges) {
if (e.getSource() == n || e.getTarget() == n) {
edgesToRemove.add(e);
area.removeComponent(e);
}
}
edges.removeAll(edgesToRemove);
area.removeComponent(nodes.get(n));
nodes.remove(n);
updateLinesAndEdgePositions();
updateQuery();
}
public String getAQLQuery() {
StringBuilder query = new StringBuilder();
StringBuffer nodeIdentityOperations = new StringBuffer();
Map<NodeWindow, Integer> nodeComponentMap = new HashMap<>();
// creating node definitions
int componentCount = 0;
for (NodeWindow nodeWindow : nodes.keySet()) {
List<NodeWindow.ConstraintLayout> constraints = nodeWindow.getConstraints();
if (componentCount++ > 0) {
query.append(" & ");
}
if (constraints.size() > 0) {
int nodeComponentCount = 0;
for (NodeWindow.ConstraintLayout c : constraints) {
if (nodeComponentCount++ > 0) {
nodeIdentityOperations.append("\n& #").append(componentCount).append(" _=_ #")
.append(componentCount + 1);
query.append(" & ");
componentCount++;
}
String operator = c.getOperator().replace("~", "=");
String quotes = c.getOperator().equals("=") || c.getOperator().equals("!=") ? "\"" : "/";
String prefix = "";
if (c.getName().trim().isEmpty() || c.getName().trim().equals("tok")) {
if (operator.equals("!=")) {
if (c.getName().trim().isEmpty()) {
prefix = "tok" + c.getName() + operator;
} else {
prefix = c.getName() + operator;
}
}
} else {
prefix = c.getName() + operator;
}
if ("".equals(c.getValue())) {
query.append(c.getName());
} else {
query.append(prefix).append(quotes).append(c.getValue()).append(quotes);
}
}
} else {
query.append("node");
}
nodeComponentMap.put(nodeWindow, componentCount);
}
query.append(nodeIdentityOperations);
// appending node relations
for (EdgeWindow edgeWindow : edges) {
query.append("\n& ");
query.append('#').append(nodeComponentMap.get(edgeWindow.getSource())).append(" ")
.append(edgeWindow.getOperator()).append(" ").append("#")
.append(nodeComponentMap.get(edgeWindow.getTarget()));
}
return query.toString();
}
public Set<String> getAvailableAnnotationNames() {
Set<String> result = new TreeSet<>();
WebResource service = Helper.getAnnisWebResource(UI.getCurrent());
// get current corpus selection
Collection<String> corpusSelection = controller.getState().getSelectedCorpora();
if (service != null && corpusSelection != null) {
try {
List<AnnisAttribute> atts = new LinkedList<>();
for (String corpus : corpusSelection) {
atts.addAll(service.path("query").path("corpora").path(corpus).path("annotations")
.queryParam("fetchvalues", "false").queryParam("onlymostfrequentvalues", "true")
.get(new AnnisAttributeListType()));
}
for (AnnisAttribute a : atts) {
if (a.getType() == AnnisAttribute.Type.node) {
result.add(a.getName());
}
}
} catch (UniformInterfaceException | ClientHandlerException ex) {
log.error(null, ex);
}
}
return result;
}
public void prepareAddingEdge(NodeWindow sourceNode) {
preparedEdgeSource = sourceNode;
for (NodeWindow w : nodes.keySet()) {
if (w != sourceNode) {
w.setPrepareEdgeDock(true);
}
}
}
public void updateLinesAndEdgePositions() {
canvas.getLines().clear();
for (EdgeWindow e : edges) {
GripDragComponent w1 = nodes.get(e.getSource());
GripDragComponent w2 = nodes.get(e.getTarget());
ComponentPosition p1 = area.getPosition(w1);
ComponentPosition p2 = area.getPosition(w2);
float x1 = p1.getLeftValue() + (w1.getWidth() / 2);
float y1 = p1.getTopValue() + (w1.getHeight() / 2);
float x2 = p2.getLeftValue() + (w2.getWidth() / 2);
float y2 = p2.getTopValue() + (w2.getHeight() / 2);
float v_x = x2 - x1;
float v_y = y2 - y1;
// add line
canvas.getLines().add(new Line2D.Float(x1, y1, x2, y2));
// set position on half of the line for the edge window
ComponentPosition posEdge = area.getPosition(e);
float vectorLength = (float) Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
float xM = x1 + (vectorLength / 2.0f) * ((x2 - x1) / vectorLength);
float yM = y1 + (vectorLength / 2.0f) * ((y2 - y1) / vectorLength);
double normV_x = v_x / vectorLength;
double normV_y = v_y / vectorLength;
double pos1_x = (2.1 * vectorLength / 3) * normV_x + x1;
double pos1_y = (2.1 * vectorLength / 3) * normV_y + y1;
double origDir = Math.atan2(normV_y, normV_x);
double pos2_x = ((1 * vectorLength) / 3) * normV_x + x1;
double pos2_y = ((1 * vectorLength) / 3) * normV_y + y1;
canvas.getLines().addAll(createArrow(pos1_x, pos1_y, origDir, 20.0));
canvas.getLines().addAll(createArrow(pos2_x, pos2_y, origDir, 20.0));
posEdge.setLeftValue(xM - e.getWidth() / 2.0f);
posEdge.setTopValue(yM - e.getHeight() / 2.0f);
}
canvas.markAsDirty();
}
public void updateQuery() {
controller.getState().getAql().setValue(getAQLQuery());
}
} | Use new API to get annotation nmaes in tiger query builder
| annis-gui/src/main/java/annis/gui/querybuilder/TigerQueryBuilderCanvas.java | Use new API to get annotation nmaes in tiger query builder | <ide><path>nnis-gui/src/main/java/annis/gui/querybuilder/TigerQueryBuilderCanvas.java
<ide> /*
<ide> * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin.
<ide> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
<add> * in compliance with the License. You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License
<add> * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
<add> * or implied. See the License for the specific language governing permissions and limitations under
<add> * the License.
<ide> */
<ide> package annis.gui.querybuilder;
<ide>
<ide> import annis.gui.widgets.GripDragComponent;
<ide> import annis.gui.widgets.SimpleCanvas;
<ide> import annis.libgui.Helper;
<del>import annis.service.objects.AnnisAttribute;
<ide> import com.sun.jersey.api.client.ClientHandlerException;
<del>import com.sun.jersey.api.client.GenericType;
<ide> import com.sun.jersey.api.client.UniformInterfaceException;
<del>import com.sun.jersey.api.client.WebResource;
<ide> import com.vaadin.event.dd.DragAndDropEvent;
<ide> import com.vaadin.event.dd.DropHandler;
<ide> import com.vaadin.event.dd.acceptcriteria.AcceptAll;
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide> import java.util.TreeSet;
<add>import org.corpus_tools.annis.ApiException;
<add>import org.corpus_tools.annis.api.CorporaApi;
<add>import org.corpus_tools.annis.api.model.Annotation;
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide> /**
<ide> */
<ide> public class TigerQueryBuilderCanvas extends Panel {
<ide>
<del> private static class AbsoluteDropHandler implements DropHandler {
<del>
<del> /**
<del> *
<del> */
<del> private static final long serialVersionUID = 8456460938439624526L;
<del> private AbsoluteLayout layout;
<del> private TigerQueryBuilderCanvas parent;
<del>
<del> public AbsoluteDropHandler(TigerQueryBuilderCanvas parent, AbsoluteLayout layout) {
<del> this.layout = layout;
<del> this.parent = parent;
<del> }
<del>
<del> @Override
<del> public void drop(DragAndDropEvent event) {
<del> GripDragComponent.MouseEventTransferable t = (GripDragComponent.MouseEventTransferable) event
<del> .getTransferable();
<del> WrapperTargetDetails details = (WrapperTargetDetails) event.getTargetDetails();
<del>
<del> if (t == null || details == null) {
<del> return;
<del> }
<del>
<del> int xChange = details.getMouseEvent().getClientX() - t.getClientX();
<del> int yChange = details.getMouseEvent().getClientY() - t.getClientY();
<del>
<del> // Move the component in the absolute layout
<del> ComponentPosition pos = layout.getPosition(t.getSourceComponent().getParent());
<del> pos.setLeftValue(pos.getLeftValue() + xChange);
<del> pos.setTopValue(pos.getTopValue() + yChange);
<del>
<del> if (parent != null) {
<del> parent.updateLinesAndEdgePositions();
<del> parent.requestRepaint();
<del>
<del> }
<del>
<del> }
<del>
<del> @Override
<del> public AcceptCriterion getAcceptCriterion() {
<del> return AcceptAll.get();
<del> }
<del> }
<del>
<del> private static class AnnisAttributeListType extends GenericType<List<AnnisAttribute>> {
<del>
<del> public AnnisAttributeListType() {}
<del> }
<add> private static class AbsoluteDropHandler implements DropHandler {
<ide>
<ide> /**
<ide> *
<ide> */
<del> private static final long serialVersionUID = 4564976366028699909L;
<del> private static final org.slf4j.Logger log = LoggerFactory.getLogger(TigerQueryBuilderCanvas.class);
<del> private SimpleCanvas canvas;
<del> private Map<NodeWindow, GripDragComponent> nodes;
<del> private List<EdgeWindow> edges;
<del> private AbsoluteLayout area;
<del> private AbsoluteDropHandler handler;
<del> private int number = 0;
<del>
<del> private NodeWindow preparedEdgeSource = null;
<del>
<del> private final QueryController controller;
<del>
<del> public TigerQueryBuilderCanvas(QueryController controller) {
<del> this.controller = controller;
<del>
<del> nodes = new HashMap<>();
<del> edges = new ArrayList<>();
<del>
<del> setSizeFull();
<del>
<del> area = new AbsoluteLayout();
<del> area.setWidth("2000px");
<del> area.setHeight("2000px");
<del> area.addStyleName("no-vertical-drag-hints");
<del> area.addStyleName("no-horizontal-drag-hints");
<del> area.addStyleName("no-box-drag-hints");
<del>
<del> canvas = new SimpleCanvas();
<del> canvas.setSizeFull();
<del> canvas.addStyleName("tigerquery-builder-canvas");
<del>
<del> handler = new AbsoluteDropHandler(this, area);
<del>
<del> DragAndDropWrapper areaPane = new DragAndDropWrapper(area);
<del> areaPane.setWidth("2000px");
<del> areaPane.setHeight("2000px");
<del> areaPane.setDropHandler(handler);
<del>
<del> area.addComponent(canvas, "top:0px;left:0px");
<del>
<del> setContent(areaPane);
<del>
<del> addStyleName("no-vertical-drag-hints");
<del> addStyleName("no-horizontal-drag-hints");
<del> addStyleName("no-box-drag-hints");
<del> }
<del>
<del> public void addEdge(NodeWindow target) {
<del> for (NodeWindow w : nodes.keySet()) {
<del> w.setPrepareEdgeDock(false);
<add> private static final long serialVersionUID = 8456460938439624526L;
<add> private AbsoluteLayout layout;
<add> private TigerQueryBuilderCanvas parent;
<add>
<add> public AbsoluteDropHandler(TigerQueryBuilderCanvas parent, AbsoluteLayout layout) {
<add> this.layout = layout;
<add> this.parent = parent;
<add> }
<add>
<add> @Override
<add> public void drop(DragAndDropEvent event) {
<add> GripDragComponent.MouseEventTransferable t =
<add> (GripDragComponent.MouseEventTransferable) event.getTransferable();
<add> WrapperTargetDetails details = (WrapperTargetDetails) event.getTargetDetails();
<add>
<add> if (t == null || details == null) {
<add> return;
<add> }
<add>
<add> int xChange = details.getMouseEvent().getClientX() - t.getClientX();
<add> int yChange = details.getMouseEvent().getClientY() - t.getClientY();
<add>
<add> // Move the component in the absolute layout
<add> ComponentPosition pos = layout.getPosition(t.getSourceComponent().getParent());
<add> pos.setLeftValue(pos.getLeftValue() + xChange);
<add> pos.setTopValue(pos.getTopValue() + yChange);
<add>
<add> if (parent != null) {
<add> parent.updateLinesAndEdgePositions();
<add> parent.requestRepaint();
<add>
<add> }
<add>
<add> }
<add>
<add> @Override
<add> public AcceptCriterion getAcceptCriterion() {
<add> return AcceptAll.get();
<add> }
<add> }
<add>
<add>
<add> /**
<add> *
<add> */
<add> private static final long serialVersionUID = 4564976366028699909L;
<add> private static final org.slf4j.Logger log =
<add> LoggerFactory.getLogger(TigerQueryBuilderCanvas.class);
<add> private SimpleCanvas canvas;
<add> private Map<NodeWindow, GripDragComponent> nodes;
<add> private List<EdgeWindow> edges;
<add> private AbsoluteLayout area;
<add> private AbsoluteDropHandler handler;
<add> private int number = 0;
<add>
<add> private NodeWindow preparedEdgeSource = null;
<add>
<add> private final QueryController controller;
<add>
<add> public TigerQueryBuilderCanvas(QueryController controller) {
<add> this.controller = controller;
<add>
<add> nodes = new HashMap<>();
<add> edges = new ArrayList<>();
<add>
<add> setSizeFull();
<add>
<add> area = new AbsoluteLayout();
<add> area.setWidth("2000px");
<add> area.setHeight("2000px");
<add> area.addStyleName("no-vertical-drag-hints");
<add> area.addStyleName("no-horizontal-drag-hints");
<add> area.addStyleName("no-box-drag-hints");
<add>
<add> canvas = new SimpleCanvas();
<add> canvas.setSizeFull();
<add> canvas.addStyleName("tigerquery-builder-canvas");
<add>
<add> handler = new AbsoluteDropHandler(this, area);
<add>
<add> DragAndDropWrapper areaPane = new DragAndDropWrapper(area);
<add> areaPane.setWidth("2000px");
<add> areaPane.setHeight("2000px");
<add> areaPane.setDropHandler(handler);
<add>
<add> area.addComponent(canvas, "top:0px;left:0px");
<add>
<add> setContent(areaPane);
<add>
<add> addStyleName("no-vertical-drag-hints");
<add> addStyleName("no-horizontal-drag-hints");
<add> addStyleName("no-box-drag-hints");
<add> }
<add>
<add> public void addEdge(NodeWindow target) {
<add> for (NodeWindow w : nodes.keySet()) {
<add> w.setPrepareEdgeDock(false);
<add> }
<add>
<add> if (preparedEdgeSource != target) {
<add> boolean valid = true;
<add> for (EdgeWindow e : edges) {
<add> if (e.getSource() == preparedEdgeSource && e.getTarget() == target) {
<add> valid = false;
<add> break;
<ide> }
<del>
<del> if (preparedEdgeSource != target) {
<del> boolean valid = true;
<del> for (EdgeWindow e : edges) {
<del> if (e.getSource() == preparedEdgeSource && e.getTarget() == target) {
<del> valid = false;
<del> break;
<del> }
<del> }
<del> if (valid) {
<del> EdgeWindow e = new EdgeWindow(this, preparedEdgeSource, target);
<del> e.setWidth("170px");
<del> e.setHeight("80px");
<del> e.addStyleName("tigerquery-builder-overlay");
<del> edges.add(e);
<del> area.addComponent(e);
<del> updateLinesAndEdgePositions();
<del> updateQuery();
<del> } else {
<del> Notification.show("There is already such an edge", Notification.Type.WARNING_MESSAGE);
<del> }
<del> }
<del> }
<del>
<del> public void addNode() {
<del> final NodeWindow n = new NodeWindow(number++, this);
<del>
<del> GripDragComponent panel = new GripDragComponent(n);
<del> panel.setWidth(NodeWindow.WIDTH, Layout.Unit.PIXELS);
<del> panel.setHeight(NodeWindow.HEIGHT, Layout.Unit.PIXELS);
<del> nodes.put(n, panel);
<del> area.addComponent(panel, "top:" + (10 + ((NodeWindow.HEIGHT + 20) * (number - 1))) + "px;left:10px");
<del> // area.addComponent(wrapper, "top:" + (10 + (120 * (number-1))) +
<del> // "px;left:10px");
<del> updateQuery();
<del> }
<del>
<del> public void clearAll() {
<del> for (EdgeWindow w : edges) {
<del> area.removeComponent(w);
<del> }
<del> edges.clear();
<del>
<del> for (GripDragComponent w : nodes.values()) {
<del> area.removeComponent(w);
<del> }
<del> nodes.clear();
<del> number = 0;
<del>
<add> }
<add> if (valid) {
<add> EdgeWindow e = new EdgeWindow(this, preparedEdgeSource, target);
<add> e.setWidth("170px");
<add> e.setHeight("80px");
<add> e.addStyleName("tigerquery-builder-overlay");
<add> edges.add(e);
<add> area.addComponent(e);
<ide> updateLinesAndEdgePositions();
<ide> updateQuery();
<del> }
<del>
<del> private List<Line2D> createArrow(double x, double y, double direction, double arrowLength) {
<del> LinkedList<Line2D> result = new LinkedList<>();
<del>
<del> double dir1 = direction + Math.PI / 8.0;
<del> double dir2 = direction - Math.PI / 8.0;
<del>
<del> double end1_x = x - arrowLength * Math.cos(dir1);
<del> double end1_y = y - arrowLength * Math.sin(dir1);
<del>
<del> double end2_x = x - arrowLength * Math.cos(dir2);
<del> double end2_y = y - arrowLength * Math.sin(dir2);
<del>
<del> result.add(new Line2D.Double(x, y, end1_x, end1_y));
<del> result.add(new Line2D.Double(x, y, end2_x, end2_y));
<del>
<del> return result;
<del> }
<del>
<del> public void deleteEdge(EdgeWindow e) {
<add> } else {
<add> Notification.show("There is already such an edge", Notification.Type.WARNING_MESSAGE);
<add> }
<add> }
<add> }
<add>
<add> public void addNode() {
<add> final NodeWindow n = new NodeWindow(number++, this);
<add>
<add> GripDragComponent panel = new GripDragComponent(n);
<add> panel.setWidth(NodeWindow.WIDTH, Layout.Unit.PIXELS);
<add> panel.setHeight(NodeWindow.HEIGHT, Layout.Unit.PIXELS);
<add> nodes.put(n, panel);
<add> area.addComponent(panel,
<add> "top:" + (10 + ((NodeWindow.HEIGHT + 20) * (number - 1))) + "px;left:10px");
<add> // area.addComponent(wrapper, "top:" + (10 + (120 * (number-1))) +
<add> // "px;left:10px");
<add> updateQuery();
<add> }
<add>
<add> public void clearAll() {
<add> for (EdgeWindow w : edges) {
<add> area.removeComponent(w);
<add> }
<add> edges.clear();
<add>
<add> for (GripDragComponent w : nodes.values()) {
<add> area.removeComponent(w);
<add> }
<add> nodes.clear();
<add> number = 0;
<add>
<add> updateLinesAndEdgePositions();
<add> updateQuery();
<add> }
<add>
<add> private List<Line2D> createArrow(double x, double y, double direction, double arrowLength) {
<add> LinkedList<Line2D> result = new LinkedList<>();
<add>
<add> double dir1 = direction + Math.PI / 8.0;
<add> double dir2 = direction - Math.PI / 8.0;
<add>
<add> double end1_x = x - arrowLength * Math.cos(dir1);
<add> double end1_y = y - arrowLength * Math.sin(dir1);
<add>
<add> double end2_x = x - arrowLength * Math.cos(dir2);
<add> double end2_y = y - arrowLength * Math.sin(dir2);
<add>
<add> result.add(new Line2D.Double(x, y, end1_x, end1_y));
<add> result.add(new Line2D.Double(x, y, end2_x, end2_y));
<add>
<add> return result;
<add> }
<add>
<add> public void deleteEdge(EdgeWindow e) {
<add> area.removeComponent(e);
<add> edges.remove(e);
<add> updateLinesAndEdgePositions();
<add> updateQuery();
<add> }
<add>
<add> public void deleteNode(NodeWindow n) {
<add> LinkedList<EdgeWindow> edgesToRemove = new LinkedList<>();
<add> for (EdgeWindow e : edges) {
<add> if (e.getSource() == n || e.getTarget() == n) {
<add> edgesToRemove.add(e);
<ide> area.removeComponent(e);
<del> edges.remove(e);
<del> updateLinesAndEdgePositions();
<del> updateQuery();
<del> }
<del>
<del> public void deleteNode(NodeWindow n) {
<del> LinkedList<EdgeWindow> edgesToRemove = new LinkedList<>();
<del> for (EdgeWindow e : edges) {
<del> if (e.getSource() == n || e.getTarget() == n) {
<del> edgesToRemove.add(e);
<del> area.removeComponent(e);
<add> }
<add> }
<add>
<add> edges.removeAll(edgesToRemove);
<add>
<add> area.removeComponent(nodes.get(n));
<add> nodes.remove(n);
<add> updateLinesAndEdgePositions();
<add> updateQuery();
<add> }
<add>
<add> public String getAQLQuery() {
<add> StringBuilder query = new StringBuilder();
<add> StringBuffer nodeIdentityOperations = new StringBuffer();
<add> Map<NodeWindow, Integer> nodeComponentMap = new HashMap<>();
<add>
<add> // creating node definitions
<add> int componentCount = 0;
<add> for (NodeWindow nodeWindow : nodes.keySet()) {
<add> List<NodeWindow.ConstraintLayout> constraints = nodeWindow.getConstraints();
<add>
<add> if (componentCount++ > 0) {
<add> query.append(" & ");
<add> }
<add>
<add> if (constraints.size() > 0) {
<add> int nodeComponentCount = 0;
<add> for (NodeWindow.ConstraintLayout c : constraints) {
<add> if (nodeComponentCount++ > 0) {
<add> nodeIdentityOperations.append("\n& #").append(componentCount).append(" _=_ #")
<add> .append(componentCount + 1);
<add> query.append(" & ");
<add> componentCount++;
<add> }
<add> String operator = c.getOperator().replace("~", "=");
<add> String quotes = c.getOperator().equals("=") || c.getOperator().equals("!=") ? "\"" : "/";
<add> String prefix = "";
<add> if (c.getName().trim().isEmpty() || c.getName().trim().equals("tok")) {
<add> if (operator.equals("!=")) {
<add> if (c.getName().trim().isEmpty()) {
<add> prefix = "tok" + c.getName() + operator;
<add> } else {
<add> prefix = c.getName() + operator;
<add> }
<ide> }
<add> } else {
<add> prefix = c.getName() + operator;
<add> }
<add> if ("".equals(c.getValue())) {
<add> query.append(c.getName());
<add> } else {
<add> query.append(prefix).append(quotes).append(c.getValue()).append(quotes);
<add> }
<ide> }
<del>
<del> edges.removeAll(edgesToRemove);
<del>
<del> area.removeComponent(nodes.get(n));
<del> nodes.remove(n);
<del> updateLinesAndEdgePositions();
<del> updateQuery();
<del> }
<del>
<del> public String getAQLQuery() {
<del> StringBuilder query = new StringBuilder();
<del> StringBuffer nodeIdentityOperations = new StringBuffer();
<del> Map<NodeWindow, Integer> nodeComponentMap = new HashMap<>();
<del>
<del> // creating node definitions
<del> int componentCount = 0;
<del> for (NodeWindow nodeWindow : nodes.keySet()) {
<del> List<NodeWindow.ConstraintLayout> constraints = nodeWindow.getConstraints();
<del>
<del> if (componentCount++ > 0) {
<del> query.append(" & ");
<add> } else {
<add> query.append("node");
<add> }
<add> nodeComponentMap.put(nodeWindow, componentCount);
<add> }
<add> query.append(nodeIdentityOperations);
<add>
<add> // appending node relations
<add> for (EdgeWindow edgeWindow : edges) {
<add> query.append("\n& ");
<add> query.append('#').append(nodeComponentMap.get(edgeWindow.getSource())).append(" ")
<add> .append(edgeWindow.getOperator()).append(" ").append("#")
<add> .append(nodeComponentMap.get(edgeWindow.getTarget()));
<add> }
<add>
<add> return query.toString();
<add> }
<add>
<add> public Set<String> getAvailableAnnotationNames() {
<add> Set<String> result = new TreeSet<>();
<add>
<add> CorporaApi api = new CorporaApi(Helper.getClient(UI.getCurrent()));
<add>
<add> // get current corpus selection
<add> Collection<String> corpusSelection = controller.getState().getSelectedCorpora();
<add>
<add> if (corpusSelection != null) {
<add> try {
<add> for (String corpus : corpusSelection) {
<add> try {
<add> for (Annotation anno : api.corpusNodeAnnotations(corpus, false, true)) {
<add> result.add(anno.getKey().getName());
<ide> }
<del>
<del> if (constraints.size() > 0) {
<del> int nodeComponentCount = 0;
<del> for (NodeWindow.ConstraintLayout c : constraints) {
<del> if (nodeComponentCount++ > 0) {
<del> nodeIdentityOperations.append("\n& #").append(componentCount).append(" _=_ #")
<del> .append(componentCount + 1);
<del> query.append(" & ");
<del> componentCount++;
<del> }
<del> String operator = c.getOperator().replace("~", "=");
<del> String quotes = c.getOperator().equals("=") || c.getOperator().equals("!=") ? "\"" : "/";
<del> String prefix = "";
<del> if (c.getName().trim().isEmpty() || c.getName().trim().equals("tok")) {
<del> if (operator.equals("!=")) {
<del> if (c.getName().trim().isEmpty()) {
<del> prefix = "tok" + c.getName() + operator;
<del> } else {
<del> prefix = c.getName() + operator;
<del> }
<del> }
<del> } else {
<del> prefix = c.getName() + operator;
<del> }
<del> if ("".equals(c.getValue())) {
<del> query.append(c.getName());
<del> } else {
<del> query.append(prefix).append(quotes).append(c.getValue()).append(quotes);
<del> }
<del> }
<del> } else {
<del> query.append("node");
<del> }
<del> nodeComponentMap.put(nodeWindow, componentCount);
<add> } catch (ApiException ex) {
<add> log.error("Could not get node annotations for corpus " + corpus, ex);
<add> }
<ide> }
<del> query.append(nodeIdentityOperations);
<del>
<del> // appending node relations
<del> for (EdgeWindow edgeWindow : edges) {
<del> query.append("\n& ");
<del> query.append('#').append(nodeComponentMap.get(edgeWindow.getSource())).append(" ")
<del> .append(edgeWindow.getOperator()).append(" ").append("#")
<del> .append(nodeComponentMap.get(edgeWindow.getTarget()));
<del> }
<del>
<del> return query.toString();
<del> }
<del>
<del> public Set<String> getAvailableAnnotationNames() {
<del> Set<String> result = new TreeSet<>();
<del>
<del> WebResource service = Helper.getAnnisWebResource(UI.getCurrent());
<del>
<del> // get current corpus selection
<del> Collection<String> corpusSelection = controller.getState().getSelectedCorpora();
<del>
<del> if (service != null && corpusSelection != null) {
<del> try {
<del> List<AnnisAttribute> atts = new LinkedList<>();
<del>
<del> for (String corpus : corpusSelection) {
<del> atts.addAll(service.path("query").path("corpora").path(corpus).path("annotations")
<del> .queryParam("fetchvalues", "false").queryParam("onlymostfrequentvalues", "true")
<del> .get(new AnnisAttributeListType()));
<del> }
<del>
<del> for (AnnisAttribute a : atts) {
<del> if (a.getType() == AnnisAttribute.Type.node) {
<del> result.add(a.getName());
<del> }
<del> }
<del>
<del> } catch (UniformInterfaceException | ClientHandlerException ex) {
<del> log.error(null, ex);
<del> }
<del> }
<del> return result;
<del> }
<del>
<del> public void prepareAddingEdge(NodeWindow sourceNode) {
<del> preparedEdgeSource = sourceNode;
<del> for (NodeWindow w : nodes.keySet()) {
<del> if (w != sourceNode) {
<del> w.setPrepareEdgeDock(true);
<del> }
<del> }
<del> }
<del>
<del> public void updateLinesAndEdgePositions() {
<del> canvas.getLines().clear();
<del>
<del> for (EdgeWindow e : edges) {
<del> GripDragComponent w1 = nodes.get(e.getSource());
<del> GripDragComponent w2 = nodes.get(e.getTarget());
<del>
<del> ComponentPosition p1 = area.getPosition(w1);
<del> ComponentPosition p2 = area.getPosition(w2);
<del>
<del> float x1 = p1.getLeftValue() + (w1.getWidth() / 2);
<del> float y1 = p1.getTopValue() + (w1.getHeight() / 2);
<del> float x2 = p2.getLeftValue() + (w2.getWidth() / 2);
<del> float y2 = p2.getTopValue() + (w2.getHeight() / 2);
<del>
<del> float v_x = x2 - x1;
<del> float v_y = y2 - y1;
<del>
<del> // add line
<del> canvas.getLines().add(new Line2D.Float(x1, y1, x2, y2));
<del>
<del> // set position on half of the line for the edge window
<del> ComponentPosition posEdge = area.getPosition(e);
<del>
<del> float vectorLength = (float) Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
<del> float xM = x1 + (vectorLength / 2.0f) * ((x2 - x1) / vectorLength);
<del> float yM = y1 + (vectorLength / 2.0f) * ((y2 - y1) / vectorLength);
<del>
<del> double normV_x = v_x / vectorLength;
<del> double normV_y = v_y / vectorLength;
<del>
<del> double pos1_x = (2.1 * vectorLength / 3) * normV_x + x1;
<del> double pos1_y = (2.1 * vectorLength / 3) * normV_y + y1;
<del> double origDir = Math.atan2(normV_y, normV_x);
<del>
<del> double pos2_x = ((1 * vectorLength) / 3) * normV_x + x1;
<del> double pos2_y = ((1 * vectorLength) / 3) * normV_y + y1;
<del>
<del> canvas.getLines().addAll(createArrow(pos1_x, pos1_y, origDir, 20.0));
<del> canvas.getLines().addAll(createArrow(pos2_x, pos2_y, origDir, 20.0));
<del>
<del> posEdge.setLeftValue(xM - e.getWidth() / 2.0f);
<del> posEdge.setTopValue(yM - e.getHeight() / 2.0f);
<del> }
<del>
<del> canvas.markAsDirty();
<del> }
<del>
<del> public void updateQuery() {
<del> controller.getState().getAql().setValue(getAQLQuery());
<del> }
<add> } catch (UniformInterfaceException | ClientHandlerException ex) {
<add> log.error(null, ex);
<add> }
<add> }
<add> return result;
<add> }
<add>
<add> public void prepareAddingEdge(NodeWindow sourceNode) {
<add> preparedEdgeSource = sourceNode;
<add> for (NodeWindow w : nodes.keySet()) {
<add> if (w != sourceNode) {
<add> w.setPrepareEdgeDock(true);
<add> }
<add> }
<add> }
<add>
<add> public void updateLinesAndEdgePositions() {
<add> canvas.getLines().clear();
<add>
<add> for (EdgeWindow e : edges) {
<add> GripDragComponent w1 = nodes.get(e.getSource());
<add> GripDragComponent w2 = nodes.get(e.getTarget());
<add>
<add> ComponentPosition p1 = area.getPosition(w1);
<add> ComponentPosition p2 = area.getPosition(w2);
<add>
<add> float x1 = p1.getLeftValue() + (w1.getWidth() / 2);
<add> float y1 = p1.getTopValue() + (w1.getHeight() / 2);
<add> float x2 = p2.getLeftValue() + (w2.getWidth() / 2);
<add> float y2 = p2.getTopValue() + (w2.getHeight() / 2);
<add>
<add> float v_x = x2 - x1;
<add> float v_y = y2 - y1;
<add>
<add> // add line
<add> canvas.getLines().add(new Line2D.Float(x1, y1, x2, y2));
<add>
<add> // set position on half of the line for the edge window
<add> ComponentPosition posEdge = area.getPosition(e);
<add>
<add> float vectorLength = (float) Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
<add> float xM = x1 + (vectorLength / 2.0f) * ((x2 - x1) / vectorLength);
<add> float yM = y1 + (vectorLength / 2.0f) * ((y2 - y1) / vectorLength);
<add>
<add> double normV_x = v_x / vectorLength;
<add> double normV_y = v_y / vectorLength;
<add>
<add> double pos1_x = (2.1 * vectorLength / 3) * normV_x + x1;
<add> double pos1_y = (2.1 * vectorLength / 3) * normV_y + y1;
<add> double origDir = Math.atan2(normV_y, normV_x);
<add>
<add> double pos2_x = ((1 * vectorLength) / 3) * normV_x + x1;
<add> double pos2_y = ((1 * vectorLength) / 3) * normV_y + y1;
<add>
<add> canvas.getLines().addAll(createArrow(pos1_x, pos1_y, origDir, 20.0));
<add> canvas.getLines().addAll(createArrow(pos2_x, pos2_y, origDir, 20.0));
<add>
<add> posEdge.setLeftValue(xM - e.getWidth() / 2.0f);
<add> posEdge.setTopValue(yM - e.getHeight() / 2.0f);
<add> }
<add>
<add> canvas.markAsDirty();
<add> }
<add>
<add> public void updateQuery() {
<add> controller.getState().getAql().setValue(getAQLQuery());
<add> }
<ide> } |
|
JavaScript | mpl-2.0 | bb415915a44a4d06374696b9d0e32fecf5ba4866 | 0 | asamuzaK/sidebarTabs,asamuzaK/sidebarTabs | /*
* util.js
*/
/* shared */
import { getType, isObjectNotEmpty, isString } from './common.js';
import {
getActiveTabId, getCloseTabsByDoubleClickValue, getCurrentWindow,
getSessionWindowValue, getWindow, setSessionWindowValue, setStorage, updateTab
} from './browser.js';
import { ports } from './port.js';
import {
CLASS_HEADING, CLASS_HEADING_LABEL, CLASS_TAB_COLLAPSED,
CLASS_TAB_CONTAINER, CLASS_TAB_CONTAINER_TMPL, CLASS_TAB_GROUP,
NEW_TAB, PINNED, SESSION_SAVE, SIDEBAR, TAB_LIST, TAB_QUERY
} from './constant.js';
import { parse as parseTld } from '../lib/tldts/index.esm.min.js';
/**
* get template
*
* @param {string} id - template ID
* @returns {object} - document fragment
*/
export const getTemplate = id => {
if (!isString(id)) {
throw new TypeError(`Expected String but got ${getType(id)}.`);
}
const tmpl = document.getElementById(id);
let frag;
if (tmpl) {
const { content: { firstElementChild } } = tmpl;
frag = document.importNode(firstElementChild, true);
}
return frag || null;
};
/**
* get sidebar tab container from parent node
*
* @param {object} node - node
* @returns {object} - sidebar tab container
*/
export const getSidebarTabContainer = node => {
let container;
while (node && node.parentNode) {
const { classList, parentNode } = node;
if (classList.contains(CLASS_TAB_CONTAINER)) {
container = node;
break;
}
node = parentNode;
}
return container || null;
};
/**
* restore sidebar tab container
*
* @param {object} container - tab container
* @returns {void}
*/
export const restoreTabContainer = container => {
if (container && container.nodeType === Node.ELEMENT_NODE) {
const { childElementCount, classList, parentNode } = container;
switch (childElementCount) {
case 0:
parentNode.removeChild(container);
break;
case 1:
classList.remove(CLASS_TAB_GROUP);
break;
default:
}
}
};
/**
* create sidebar tab
*
* @param {object} node - node
* @param {object} [target] - target element to insert before
* @returns {object} - sidebar tab
*/
export const createSidebarTab = (node, target) => {
let tab;
if (node && node.nodeType === Node.ELEMENT_NODE) {
const container = getTemplate(CLASS_TAB_CONTAINER_TMPL);
tab = node;
container.appendChild(tab);
container.removeAttribute('hidden');
if (!target || target.nodeType !== Node.ELEMENT_NODE ||
!target.classList.contains(CLASS_TAB_CONTAINER)) {
target = document.getElementById(NEW_TAB);
}
target.parentNode.insertBefore(container, target);
}
return tab || null;
};
/**
* get sidebar tab from parent node
*
* @param {object} node - node
* @returns {object} - sidebar tab
*/
export const getSidebarTab = node => {
let tab;
while (node && node.parentNode) {
const { dataset, parentNode } = node;
if (dataset.tabId) {
tab = node;
break;
}
node = parentNode;
}
return tab || null;
};
/**
* get sidebar tab ID
*
* @param {object} node - node
* @returns {?number} - tab ID
*/
export const getSidebarTabId = node => {
let tabId;
while (node && node.parentNode) {
const { dataset, parentNode } = node;
if (dataset.tabId) {
tabId = dataset.tabId * 1;
break;
}
node = parentNode;
}
return tabId || null;
};
/**
* get sidebar tab IDs
*
* @param {Array} nodes - array of node
* @returns {Array} - array of tab IDs
*/
export const getSidebarTabIds = nodes => {
if (!Array.isArray(nodes)) {
throw new TypeError(`Expected Array but got ${getType(nodes)}.`);
}
const arr = [];
for (const item of nodes) {
const tabId = getSidebarTabId(item);
if (Number.isInteger(tabId)) {
arr.push(tabId);
}
}
return arr;
};
/**
* get sidebar tab index
*
* @param {object} node - node
* @returns {?number} - index
*/
export const getSidebarTabIndex = node => {
const tab = getSidebarTab(node);
let index;
if (tab) {
const items = document.querySelectorAll(TAB_QUERY);
const l = items.length;
let i = 0;
while (i < l && !Number.isInteger(index)) {
if (items[i] === tab) {
index = i;
break;
}
i++;
}
}
return Number.isInteger(index) ? index : null;
};
/**
* get tabs in range
*
* @param {object} tabA - tab A
* @param {object} tabB - tab B
* @returns {Array} - array of tabs
*/
export const getTabsInRange = (tabA, tabB) => {
const tabAIndex = getSidebarTabIndex(tabA);
const tabBIndex = getSidebarTabIndex(tabB);
const arr = [];
if (Number.isInteger(tabAIndex) && Number.isInteger(tabBIndex)) {
const items = document.querySelectorAll(TAB_QUERY);
let fromIndex, toIndex;
if (tabAIndex > tabBIndex) {
fromIndex = tabBIndex;
toIndex = tabAIndex;
} else {
fromIndex = tabAIndex;
toIndex = tabBIndex;
}
for (let i = fromIndex; i <= toIndex; i++) {
arr.push(items[i]);
}
}
return arr;
};
/**
* get next tab
*
* @param {object} elm - element
* @param {boolean} skipCollapsed - skip collapsed tab
* @returns {object} - tab
*/
export const getNextTab = (elm, skipCollapsed = false) => {
const currentTab = getSidebarTab(elm);
let tab;
if (currentTab) {
const { parentNode, nextElementSibling } = currentTab;
const { nextElementSibling: nextParent } = parentNode;
if (nextElementSibling) {
if (skipCollapsed && parentNode.classList.contains(CLASS_TAB_COLLAPSED)) {
if (nextParent && nextParent.id !== NEW_TAB) {
tab = nextParent.querySelector(TAB_QUERY);
}
} else {
tab = nextElementSibling;
}
} else if (nextParent && nextParent.id !== NEW_TAB) {
tab = nextParent.querySelector(TAB_QUERY);
}
}
return tab || null;
};
/**
* get previous tab
*
* @param {object} elm - element
* @param {boolean} skipCollapsed - skip collapsed tab
* @returns {object} - tab
*/
export const getPreviousTab = (elm, skipCollapsed = false) => {
const currentTab = getSidebarTab(elm);
let tab;
if (currentTab) {
const { parentNode, previousElementSibling } = currentTab;
const { previousElementSibling: previousParent } = parentNode;
const heading = parentNode.querySelector(`.${CLASS_HEADING}`);
if (previousElementSibling && previousElementSibling !== heading) {
tab = previousElementSibling;
} else if (previousParent) {
const items = previousParent.querySelectorAll(TAB_QUERY);
if (skipCollapsed &&
previousParent.classList.contains(CLASS_TAB_COLLAPSED)) {
[tab] = items;
} else {
tab = items[items.length - 1];
}
}
}
return tab || null;
};
/**
* is newtab
*
* @param {object} node - node
* @returns {boolean} - result
*/
export const isNewTab = node => {
let tab;
while (node && node.parentNode) {
const { id, parentNode } = node;
if (id === NEW_TAB) {
tab = node;
break;
}
node = parentNode;
}
return !!tab;
};
/**
* get tab list from sessions
*
* @param {string} key - key
* @param {number} windowId - window ID
* @returns {object} - tab list
*/
export const getSessionTabList = async (key, windowId) => {
if (!isString(key)) {
throw new TypeError(`Expected String but got ${getType(key)}.`);
}
if (!Number.isInteger(windowId)) {
const win = await getCurrentWindow();
windowId = win.id;
}
const value = await getSessionWindowValue(key, windowId);
let tabList;
if (isString(value)) {
tabList = JSON.parse(value);
}
return tabList || null;
};
/* mutex */
export const mutex = new Set();
/**
* save tab list to sessions
*
* @param {string} domStr - DOM string
* @param {number} windowId - window ID
* @returns {boolean} - saved
*/
export const saveSessionTabList = async (domStr, windowId) => {
if (!isString(domStr)) {
throw new TypeError(`Expected String but got ${getType(domStr)}.`);
}
if (!Number.isInteger(windowId)) {
throw new TypeError(`Expected Number but got ${getType(windowId)}.`);
}
const win = await getWindow(windowId);
const { incognito } = win;
let res;
if (!incognito && !mutex.has(windowId)) {
mutex.add(windowId);
try {
const tabList = {
recent: {}
};
const dom = new DOMParser().parseFromString(domStr, 'text/html');
const items =
dom.querySelectorAll(`.${CLASS_TAB_CONTAINER}:not(#${NEW_TAB})`);
const prevList = await getSessionTabList(TAB_LIST, windowId);
const l = items.length;
let i = 0;
let j = 0;
while (i < l) {
const item = items[i];
const collapsed = item.classList.contains(CLASS_TAB_COLLAPSED);
const heading = item.querySelector(`.${CLASS_HEADING}`);
const headingShown = heading && !heading.hidden;
const headingLabel =
heading &&
heading.querySelector(`.${CLASS_HEADING_LABEL}`).textContent;
const childTabs = item.querySelectorAll(TAB_QUERY);
for (const tab of childTabs) {
const tabsTab = tab.dataset.tab;
const { url } = JSON.parse(tabsTab);
tabList.recent[j] = {
collapsed,
headingLabel,
headingShown,
url,
containerIndex: i
};
j++;
}
i++;
}
if (isObjectNotEmpty(prevList) &&
Object.prototype.hasOwnProperty.call(prevList, 'recent')) {
tabList.prev = Object.assign({}, prevList.recent);
}
await setSessionWindowValue(TAB_LIST, JSON.stringify(tabList), windowId);
res = mutex.delete(windowId);
} catch (e) {
mutex.delete(windowId);
throw e;
}
}
return !!res;
};
/**
* request save session
*
* @param {number} windowId - window ID
* @returns {?Function} - port.postMessage()
*/
export const requestSaveSession = async windowId => {
let func, win;
if (Number.isInteger(windowId)) {
win = await getWindow(windowId);
} else {
win = await getCurrentWindow();
windowId = win.id;
}
const port = ports.get(`${SIDEBAR}_${windowId}`);
if (port && win && !win.incognito) {
const cloneBody = document.body.cloneNode(true);
const items =
cloneBody.querySelectorAll(`.${CLASS_TAB_CONTAINER}:not(#${NEW_TAB})`);
const frag = document.createDocumentFragment();
frag.append(...items);
if (frag.childElementCount) {
const doctype = new XMLSerializer().serializeToString(document.doctype);
const dom = new XMLSerializer().serializeToString(frag);
func = port.postMessage({
[SESSION_SAVE]: {
windowId,
domString: `${doctype}${dom}`
}
});
}
}
return func || null;
};
/**
* activate tab
*
* @param {object} elm - element
* @returns {?Function} - updateTab()
*/
export const activateTab = async elm => {
const tabId = getSidebarTabId(elm);
let func;
if (Number.isInteger(tabId)) {
func = updateTab(tabId, {
active: true
});
}
return func || null;
};
/**
* scroll tab into view
*
* @param {object} elm - Element
* @returns {void}
*/
export const scrollTabIntoView = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
const tabsTab = elm.dataset.tab;
if (tabsTab) {
const { active } = JSON.parse(tabsTab);
if (active) {
const pinned = document.getElementById(PINNED);
const newTab = document.getElementById(NEW_TAB);
const {
top: pinnedTop, bottom: pinnedBottom
} = pinned.getBoundingClientRect();
const { top: newTabTop } = newTab.getBoundingClientRect();
const { bottom: tabBottom, top: tabTop } = elm.getBoundingClientRect();
if (tabTop < pinnedBottom) {
elm.scrollIntoView({
behavior: 'smooth',
block: pinnedTop === pinnedBottom ? 'start' : 'center'
});
} else {
tabBottom > newTabTop && elm.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
}
}
}
}
};
/**
*
* switch tab
*
* @param {object} opt - options
* @returns {?Function} - activateTab()
*/
export const switchTab = async opt => {
let func;
if (isObjectNotEmpty(opt)) {
const { deltaY, skipCollapsed, windowId } = opt;
const activeTabId = await getActiveTabId(windowId);
const activeTab = document.querySelector(`[data-tab-id="${activeTabId}"]`);
if (activeTab && Number.isFinite(deltaY)) {
let targetTab;
if (deltaY > 0) {
targetTab = getNextTab(activeTab, skipCollapsed);
} else if (deltaY < 0) {
targetTab = getPreviousTab(activeTab, skipCollapsed);
}
if (targetTab) {
func = activateTab(targetTab);
}
}
}
return func || null;
};
/**
* create URL match string
*
* @param {string} url - url
* @returns {string} - match string
*/
export const createUrlMatchString = url => {
if (!isString(url)) {
throw new TypeError(`Expected String but got ${getType(url)}.`);
}
const { hostname, protocol } = new URL(url);
const { domain } = parseTld(hostname);
const isHttp = /^https?:$/.test(protocol);
let str;
if (/^file:$/.test(protocol)) {
str = 'file:///*';
} else if (isHttp) {
if (domain) {
str = `*://*.${domain}/*`;
} else {
str = `*://${hostname}/*`;
}
} else if (domain) {
str = `${protocol}//*.${domain}/*`;
} else {
str = `${protocol}//${hostname}/*`;
}
return str;
};
/**
* store closeTabsByDoubleClick user value
*
* @param {boolean} bool - browserSettings enabled
* @returns {void}
*/
export const storeCloseTabsByDoubleClickValue = async bool => {
const store = {
id: 'closeTabsByDoubleClick',
checked: false,
value: ''
};
if (bool) {
const {
levelOfControl, value: userValue
} = await getCloseTabsByDoubleClickValue();
store.checked = !!userValue;
store.value = levelOfControl;
}
return setStorage({
closeTabsByDoubleClick: store
});
};
// For test
export { ports };
| src/mjs/util.js | /*
* util.js
*/
/* shared */
import { getType, isObjectNotEmpty, isString } from './common.js';
import {
getActiveTabId, getCloseTabsByDoubleClickValue, getCurrentWindow,
getSessionWindowValue, getWindow, setSessionWindowValue, setStorage, updateTab
} from './browser.js';
import { ports } from './port.js';
import {
CLASS_HEADING, CLASS_HEADING_LABEL, CLASS_TAB_COLLAPSED,
CLASS_TAB_CONTAINER, CLASS_TAB_CONTAINER_TMPL, CLASS_TAB_GROUP,
NEW_TAB, PINNED, SESSION_SAVE, SIDEBAR, TAB_LIST, TAB_QUERY
} from './constant.js';
import { parse as parseTld } from '../lib/tldts/index.esm.min.js';
/**
* get template
*
* @param {string} id - template ID
* @returns {object} - document fragment
*/
export const getTemplate = id => {
if (!isString(id)) {
throw new TypeError(`Expected String but got ${getType(id)}.`);
}
const tmpl = document.getElementById(id);
let frag;
if (tmpl) {
const { content: { firstElementChild } } = tmpl;
frag = document.importNode(firstElementChild, true);
}
return frag || null;
};
/**
* get sidebar tab container from parent node
*
* @param {object} node - node
* @returns {object} - sidebar tab container
*/
export const getSidebarTabContainer = node => {
let container;
while (node && node.parentNode) {
const { classList, parentNode } = node;
if (classList.contains(CLASS_TAB_CONTAINER)) {
container = node;
break;
}
node = parentNode;
}
return container || null;
};
/**
* restore sidebar tab container
*
* @param {object} container - tab container
* @returns {void}
*/
export const restoreTabContainer = container => {
if (container && container.nodeType === Node.ELEMENT_NODE) {
const { childElementCount, classList, parentNode } = container;
switch (childElementCount) {
case 0:
parentNode.removeChild(container);
break;
case 1:
classList.remove(CLASS_TAB_GROUP);
break;
default:
}
}
};
/**
* create sidebar tab
*
* @param {object} node - node
* @param {object} [target] - target element to insert before
* @returns {object} - sidebar tab
*/
export const createSidebarTab = (node, target) => {
let tab;
if (node && node.nodeType === Node.ELEMENT_NODE) {
const container = getTemplate(CLASS_TAB_CONTAINER_TMPL);
tab = node;
container.appendChild(tab);
container.removeAttribute('hidden');
if (!target || target.nodeType !== Node.ELEMENT_NODE ||
!target.classList.contains(CLASS_TAB_CONTAINER)) {
target = document.getElementById(NEW_TAB);
}
target.parentNode.insertBefore(container, target);
}
return tab || null;
};
/**
* get sidebar tab from parent node
*
* @param {object} node - node
* @returns {object} - sidebar tab
*/
export const getSidebarTab = node => {
let tab;
while (node && node.parentNode) {
const { dataset, parentNode } = node;
if (dataset.tabId) {
tab = node;
break;
}
node = parentNode;
}
return tab || null;
};
/**
* get sidebar tab ID
*
* @param {object} node - node
* @returns {?number} - tab ID
*/
export const getSidebarTabId = node => {
let tabId;
while (node && node.parentNode) {
const { dataset, parentNode } = node;
if (dataset.tabId) {
tabId = dataset.tabId * 1;
break;
}
node = parentNode;
}
return tabId || null;
};
/**
* get sidebar tab IDs
*
* @param {Array} nodes - array of node
* @returns {Array} - array of tab IDs
*/
export const getSidebarTabIds = nodes => {
if (!Array.isArray(nodes)) {
throw new TypeError(`Expected Array but got ${getType(nodes)}.`);
}
const arr = [];
for (const item of nodes) {
const tabId = getSidebarTabId(item);
if (Number.isInteger(tabId)) {
arr.push(tabId);
}
}
return arr;
};
/**
* get sidebar tab index
*
* @param {object} node - node
* @returns {?number} - index
*/
export const getSidebarTabIndex = node => {
const tab = getSidebarTab(node);
let index;
if (tab) {
const items = document.querySelectorAll(TAB_QUERY);
const l = items.length;
let i = 0;
while (i < l && !Number.isInteger(index)) {
if (items[i] === tab) {
index = i;
break;
}
i++;
}
}
return Number.isInteger(index) ? index : null;
};
/**
* get tabs in range
*
* @param {object} tabA - tab A
* @param {object} tabB - tab B
* @returns {Array} - array of tabs
*/
export const getTabsInRange = (tabA, tabB) => {
const tabAIndex = getSidebarTabIndex(tabA);
const tabBIndex = getSidebarTabIndex(tabB);
const arr = [];
if (Number.isInteger(tabAIndex) && Number.isInteger(tabBIndex)) {
const items = document.querySelectorAll(TAB_QUERY);
let fromIndex, toIndex;
if (tabAIndex > tabBIndex) {
fromIndex = tabBIndex;
toIndex = tabAIndex;
} else {
fromIndex = tabAIndex;
toIndex = tabBIndex;
}
for (let i = fromIndex; i <= toIndex; i++) {
arr.push(items[i]);
}
}
return arr;
};
/**
* get next tab
*
* @param {object} elm - element
* @param {boolean} skipCollapsed - skip collapsed tab
* @returns {object} - tab
*/
export const getNextTab = (elm, skipCollapsed = false) => {
const currentTab = getSidebarTab(elm);
let tab;
if (currentTab) {
const { parentNode, nextElementSibling } = currentTab;
const { nextElementSibling: nextParent } = parentNode;
if (nextElementSibling) {
if (skipCollapsed && parentNode.classList.contains(CLASS_TAB_COLLAPSED)) {
if (nextParent && nextParent.id !== NEW_TAB) {
tab = nextParent.querySelector(TAB_QUERY);
}
} else {
tab = nextElementSibling;
}
} else if (nextParent && nextParent.id !== NEW_TAB) {
tab = nextParent.querySelector(TAB_QUERY);
}
}
return tab || null;
};
/**
* get previous tab
*
* @param {object} elm - element
* @param {boolean} skipCollapsed - skip collapsed tab
* @returns {object} - tab
*/
export const getPreviousTab = (elm, skipCollapsed = false) => {
const currentTab = getSidebarTab(elm);
let tab;
if (currentTab) {
const { parentNode, previousElementSibling } = currentTab;
const { previousElementSibling: previousParent } = parentNode;
const heading = parentNode.querySelector(`.${CLASS_HEADING}`);
if (previousElementSibling && previousElementSibling !== heading) {
tab = previousElementSibling;
} else if (previousParent) {
const items = previousParent.querySelectorAll(TAB_QUERY);
if (skipCollapsed &&
previousParent.classList.contains(CLASS_TAB_COLLAPSED)) {
[tab] = items;
} else {
tab = items[items.length - 1];
}
}
}
return tab || null;
};
/**
* is newtab
*
* @param {object} node - node
* @returns {boolean} - result
*/
export const isNewTab = node => {
let tab;
while (node && node.parentNode) {
const { id, parentNode } = node;
if (id === NEW_TAB) {
tab = node;
break;
}
node = parentNode;
}
return !!tab;
};
/**
* get tab list from sessions
*
* @param {string} key - key
* @param {number} windowId - window ID
* @returns {object} - tab list
*/
export const getSessionTabList = async (key, windowId) => {
if (!isString(key)) {
throw new TypeError(`Expected String but got ${getType(key)}.`);
}
if (!Number.isInteger(windowId)) {
const win = await getCurrentWindow();
windowId = win.id;
}
const value = await getSessionWindowValue(key, windowId);
let tabList;
if (isString(value)) {
tabList = JSON.parse(value);
}
return tabList || null;
};
/* mutex */
export const mutex = new Set();
/**
* save tab list to sessions
*
* @param {string} domStr - DOM string
* @param {number} windowId - window ID
* @returns {boolean} - saved
*/
export const saveSessionTabList = async (domStr, windowId) => {
if (!isString(domStr)) {
throw new TypeError(`Expected String but got ${getType(domStr)}.`);
}
if (!Number.isInteger(windowId)) {
throw new TypeError(`Expected Number but got ${getType(windowId)}.`);
}
const win = await getWindow(windowId);
const { incognito } = win;
let res;
if (!incognito && !mutex.has(windowId)) {
mutex.add(windowId);
try {
const tabList = {
recent: {}
};
const dom = new DOMParser().parseFromString(domStr, 'text/html');
const items =
dom.querySelectorAll(`.${CLASS_TAB_CONTAINER}:not(#${NEW_TAB})`);
const prevList = await getSessionTabList(TAB_LIST, windowId);
const l = items.length;
let i = 0;
let j = 0;
while (i < l) {
const item = items[i];
const collapsed = item.classList.contains(CLASS_TAB_COLLAPSED);
const heading = item.querySelector(`.${CLASS_HEADING}`);
const headingShown = heading && !heading.hidden;
const headingLabel =
heading &&
heading.querySelector(`.${CLASS_HEADING_LABEL}`).textContent;
const childTabs = item.querySelectorAll(TAB_QUERY);
for (const tab of childTabs) {
const tabsTab = tab.dataset.tab;
const { url } = JSON.parse(tabsTab);
tabList.recent[j] = {
collapsed,
headingLabel,
headingShown,
url,
containerIndex: i
};
j++;
}
i++;
}
if (isObjectNotEmpty(prevList) &&
Object.prototype.hasOwnProperty.call(prevList, 'recent')) {
tabList.prev = Object.assign({}, prevList.recent);
}
await setSessionWindowValue(TAB_LIST, JSON.stringify(tabList), windowId);
res = mutex.delete(windowId);
} catch (e) {
mutex.delete(windowId);
throw e;
}
}
return !!res;
};
/**
* request save session
*
* @param {number} windowId - window ID
* @returns {?Function} - port.postMessage()
*/
export const requestSaveSession = async windowId => {
let func, win;
if (Number.isInteger(windowId)) {
win = await getWindow(windowId);
} else {
win = await getCurrentWindow();
windowId = win.id;
}
const port = ports.get(`${SIDEBAR}_${windowId}`);
if (port && win && !win.incognito) {
const cloneBody = document.body.cloneNode(true);
const items =
cloneBody.querySelectorAll(`.${CLASS_TAB_CONTAINER}:not(#${NEW_TAB})`);
const frag = document.createDocumentFragment();
frag.append(...items);
if (frag.childElementCount) {
const doctype = new XMLSerializer().serializeToString(document.doctype);
const dom = new XMLSerializer().serializeToString(frag);
func = port.postMessage({
[SESSION_SAVE]: {
windowId,
domString: `${doctype}\n${dom}`
}
});
}
}
return func || null;
};
/**
* activate tab
*
* @param {object} elm - element
* @returns {?Function} - updateTab()
*/
export const activateTab = async elm => {
const tabId = getSidebarTabId(elm);
let func;
if (Number.isInteger(tabId)) {
func = updateTab(tabId, {
active: true
});
}
return func || null;
};
/**
* scroll tab into view
*
* @param {object} elm - Element
* @returns {void}
*/
export const scrollTabIntoView = async elm => {
if (elm && elm.nodeType === Node.ELEMENT_NODE) {
const tabsTab = elm.dataset.tab;
if (tabsTab) {
const { active } = JSON.parse(tabsTab);
if (active) {
const pinned = document.getElementById(PINNED);
const newTab = document.getElementById(NEW_TAB);
const {
top: pinnedTop, bottom: pinnedBottom
} = pinned.getBoundingClientRect();
const { top: newTabTop } = newTab.getBoundingClientRect();
const { bottom: tabBottom, top: tabTop } = elm.getBoundingClientRect();
if (tabTop < pinnedBottom) {
elm.scrollIntoView({
behavior: 'smooth',
block: pinnedTop === pinnedBottom ? 'start' : 'center'
});
} else {
tabBottom > newTabTop && elm.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
}
}
}
}
};
/**
*
* switch tab
*
* @param {object} opt - options
* @returns {?Function} - activateTab()
*/
export const switchTab = async opt => {
let func;
if (isObjectNotEmpty(opt)) {
const { deltaY, skipCollapsed, windowId } = opt;
const activeTabId = await getActiveTabId(windowId);
const activeTab = document.querySelector(`[data-tab-id="${activeTabId}"]`);
if (activeTab && Number.isFinite(deltaY)) {
let targetTab;
if (deltaY > 0) {
targetTab = getNextTab(activeTab, skipCollapsed);
} else if (deltaY < 0) {
targetTab = getPreviousTab(activeTab, skipCollapsed);
}
if (targetTab) {
func = activateTab(targetTab);
}
}
}
return func || null;
};
/**
* create URL match string
*
* @param {string} url - url
* @returns {string} - match string
*/
export const createUrlMatchString = url => {
if (!isString(url)) {
throw new TypeError(`Expected String but got ${getType(url)}.`);
}
const { hostname, protocol } = new URL(url);
const { domain } = parseTld(hostname);
const isHttp = /^https?:$/.test(protocol);
let str;
if (/^file:$/.test(protocol)) {
str = 'file:///*';
} else if (isHttp) {
if (domain) {
str = `*://*.${domain}/*`;
} else {
str = `*://${hostname}/*`;
}
} else if (domain) {
str = `${protocol}//*.${domain}/*`;
} else {
str = `${protocol}//${hostname}/*`;
}
return str;
};
/**
* store closeTabsByDoubleClick user value
*
* @param {boolean} bool - browserSettings enabled
* @returns {void}
*/
export const storeCloseTabsByDoubleClickValue = async bool => {
const store = {
id: 'closeTabsByDoubleClick',
checked: false,
value: ''
};
if (bool) {
const {
levelOfControl, value: userValue
} = await getCloseTabsByDoubleClickValue();
store.checked = !!userValue;
store.value = levelOfControl;
}
return setStorage({
closeTabsByDoubleClick: store
});
};
// For test
export { ports };
| Update util.js
| src/mjs/util.js | Update util.js | <ide><path>rc/mjs/util.js
<ide> func = port.postMessage({
<ide> [SESSION_SAVE]: {
<ide> windowId,
<del> domString: `${doctype}\n${dom}`
<add> domString: `${doctype}${dom}`
<ide> }
<ide> });
<ide> } |
|
Java | apache-2.0 | 318325c93b42d065e7f3aa327b54988edd2a5479 | 0 | pdrados/cas,fogbeam/cas_mirror,philliprower/cas,rkorn86/cas,pdrados/cas,Jasig/cas,leleuj/cas,fogbeam/cas_mirror,fogbeam/cas_mirror,Jasig/cas,apereo/cas,pdrados/cas,leleuj/cas,pdrados/cas,rkorn86/cas,pdrados/cas,philliprower/cas,fogbeam/cas_mirror,apereo/cas,philliprower/cas,leleuj/cas,philliprower/cas,rkorn86/cas,apereo/cas,philliprower/cas,pdrados/cas,leleuj/cas,apereo/cas,Jasig/cas,philliprower/cas,apereo/cas,rkorn86/cas,apereo/cas,fogbeam/cas_mirror,philliprower/cas,leleuj/cas,apereo/cas,Jasig/cas,leleuj/cas,fogbeam/cas_mirror | package org.apereo.cas.util;
import com.google.common.collect.Multimap;
import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.configuration.model.support.saml.sps.AbstractSamlSPProperties;
import org.apereo.cas.configuration.support.Beans;
import org.apereo.cas.services.ChainingAttributeReleasePolicy;
import org.apereo.cas.services.PrincipalAttributeRegisteredServiceUsernameProvider;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.ReturnMappedAttributeReleasePolicy;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.saml.services.SamlRegisteredService;
import org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.opensaml.saml.metadata.resolver.ChainingMetadataResolver;
import org.opensaml.saml.metadata.resolver.MetadataResolver;
import org.opensaml.saml.metadata.resolver.filter.impl.PredicateFilter;
import org.opensaml.saml.metadata.resolver.impl.AbstractBatchMetadataResolver;
import org.opensaml.saml.saml2.metadata.EntityDescriptor;
import org.opensaml.saml.saml2.metadata.SPSSODescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.StreamSupport;
/**
* This is {@link SamlSPUtils}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
public final class SamlSPUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(SamlSPUtils.class);
private SamlSPUtils() {
}
/**
* New saml service provider registration.
*
* @param sp the properties
* @param resolver the resolver
* @return the saml registered service
*/
public static SamlRegisteredService newSamlServiceProviderService(final AbstractSamlSPProperties sp,
final SamlRegisteredServiceCachingMetadataResolver resolver) {
if (StringUtils.isBlank(sp.getMetadata())) {
LOGGER.debug("Skipped registration of [{}] since no metadata location is found", sp.getName());
return null;
}
try {
final SamlRegisteredService service = new SamlRegisteredService();
service.setName(sp.getName());
service.setDescription(sp.getDescription());
service.setEvaluationOrder(Integer.MIN_VALUE);
service.setMetadataLocation(sp.getMetadata());
final List<String> attributesToRelease = new ArrayList<>(sp.getAttributes());
if (StringUtils.isNotBlank(sp.getNameIdAttribute())) {
attributesToRelease.add(sp.getNameIdAttribute());
service.setUsernameAttributeProvider(new PrincipalAttributeRegisteredServiceUsernameProvider(sp.getNameIdAttribute()));
}
if (StringUtils.isNotBlank(sp.getNameIdFormat())) {
service.setRequiredNameIdFormat(sp.getNameIdFormat());
}
final Multimap<String, String> attributes = Beans.transformPrincipalAttributesListIntoMultiMap(attributesToRelease);
final ChainingAttributeReleasePolicy policy = new ChainingAttributeReleasePolicy();
policy.addPolicy(new ReturnMappedAttributeReleasePolicy(CollectionUtils.wrap(attributes)));
service.setAttributeReleasePolicy(policy);
service.setMetadataCriteriaRoles(SPSSODescriptor.DEFAULT_ELEMENT_NAME.getLocalPart());
service.setMetadataCriteriaRemoveEmptyEntitiesDescriptors(true);
service.setMetadataCriteriaRemoveRolelessEntityDescriptors(true);
if (StringUtils.isNotBlank(sp.getSignatureLocation())) {
service.setMetadataSignatureLocation(sp.getSignatureLocation());
}
final List<String> entityIDList = determineEntityIdList(sp, resolver, service);
if (entityIDList.isEmpty()) {
LOGGER.warn("Skipped registration of [{}] since no metadata entity ids could be found", sp.getName());
return null;
}
final String entityIds = org.springframework.util.StringUtils.collectionToDelimitedString(entityIDList, "|");
service.setMetadataCriteriaDirection(PredicateFilter.Direction.INCLUDE.name());
service.setMetadataCriteriaPattern(entityIds);
LOGGER.debug("Registering saml service [{}] by entity id [{}]", sp.getName(), entityIds);
service.setServiceId(entityIds);
service.setSignAssertions(sp.isSignAssertions());
service.setSignResponses(sp.isSignResponses());
return service;
} catch (final Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private static List<String> determineEntityIdList(final AbstractSamlSPProperties sp,
final SamlRegisteredServiceCachingMetadataResolver resolver,
final SamlRegisteredService service) {
final List<String> entityIDList = sp.getEntityIds();
if (entityIDList.isEmpty()) {
final MetadataResolver metadataResolver = resolver.resolve(service);
final List<MetadataResolver> resolvers = new ArrayList<>();
if (metadataResolver instanceof ChainingMetadataResolver) {
resolvers.addAll(((ChainingMetadataResolver) metadataResolver).getResolvers());
} else {
resolvers.add(metadataResolver);
}
resolvers.forEach(r -> {
if (r instanceof AbstractBatchMetadataResolver) {
final Iterator<EntityDescriptor> it = ((AbstractBatchMetadataResolver) r).iterator();
final Optional<EntityDescriptor> descriptor =
StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.ORDERED), false)
.filter(e -> e.getSPSSODescriptor(SAMLConstants.SAML20P_NS) != null)
.findFirst();
if (descriptor.isPresent()) {
entityIDList.add(descriptor.get().getEntityID());
} else {
LOGGER.warn("Skipped registration of [{}] since no entity id could be found", sp.getName());
}
}
});
}
return entityIDList;
}
/**
* Save service only if it's not already found in the registry.
*
* @param service the service
* @param servicesManager the services manager
*/
public static void saveService(final RegisteredService service, final ServicesManager servicesManager) {
servicesManager.load();
if (servicesManager.findServiceBy(registeredService -> registeredService instanceof SamlRegisteredService
&& registeredService.getServiceId().equals(service.getServiceId())).size() == 0) {
LOGGER.info("Service [{}] does not exist in the registry and will be added.", service.getServiceId());
servicesManager.save(service);
servicesManager.load();
} else {
LOGGER.info("Service [{}] exists in the registry and will not be added again.", service.getServiceId());
}
}
}
| support/cas-server-support-saml-sp-integrations/src/main/java/org/apereo/cas/util/SamlSPUtils.java | package org.apereo.cas.util;
import com.google.common.collect.Multimap;
import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.configuration.model.support.saml.sps.AbstractSamlSPProperties;
import org.apereo.cas.configuration.support.Beans;
import org.apereo.cas.services.ChainingAttributeReleasePolicy;
import org.apereo.cas.services.PrincipalAttributeRegisteredServiceUsernameProvider;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.ReturnMappedAttributeReleasePolicy;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.saml.services.SamlRegisteredService;
import org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.opensaml.saml.metadata.resolver.ChainingMetadataResolver;
import org.opensaml.saml.metadata.resolver.MetadataResolver;
import org.opensaml.saml.metadata.resolver.filter.impl.PredicateFilter;
import org.opensaml.saml.metadata.resolver.impl.AbstractBatchMetadataResolver;
import org.opensaml.saml.saml2.metadata.EntityDescriptor;
import org.opensaml.saml.saml2.metadata.SPSSODescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.StreamSupport;
/**
* This is {@link SamlSPUtils}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
public final class SamlSPUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(SamlSPUtils.class);
private SamlSPUtils() {
}
/**
* New saml service provider registration.
*
* @param sp the properties
* @param resolver the resolver
* @return the saml registered service
*/
public static SamlRegisteredService newSamlServiceProviderService(final AbstractSamlSPProperties sp,
final SamlRegisteredServiceCachingMetadataResolver resolver) {
if (StringUtils.isBlank(sp.getMetadata())) {
LOGGER.debug("Skipped registration of [{}] since no metadata location is found", sp.getName());
return null;
}
try {
final SamlRegisteredService service = new SamlRegisteredService();
service.setName(sp.getName());
service.setDescription(sp.getDescription());
service.setEvaluationOrder(Integer.MIN_VALUE);
service.setMetadataLocation(sp.getMetadata());
final List<String> attributesToRelease = new ArrayList<>(sp.getAttributes());
if (StringUtils.isNotBlank(sp.getNameIdAttribute())) {
attributesToRelease.add(sp.getNameIdAttribute());
service.setUsernameAttributeProvider(new PrincipalAttributeRegisteredServiceUsernameProvider(sp.getNameIdAttribute()));
}
if (StringUtils.isNotBlank(sp.getNameIdFormat())) {
service.setRequiredNameIdFormat(sp.getNameIdFormat());
}
final Multimap<String, String> attributes = Beans.transformPrincipalAttributesListIntoMultiMap(attributesToRelease);
final ChainingAttributeReleasePolicy policy = new ChainingAttributeReleasePolicy();
policy.addPolicy(new ReturnMappedAttributeReleasePolicy(CollectionUtils.wrap(attributes)));
service.setAttributeReleasePolicy(policy);
service.setMetadataCriteriaRoles(SPSSODescriptor.DEFAULT_ELEMENT_NAME.getLocalPart());
service.setMetadataCriteriaRemoveEmptyEntitiesDescriptors(true);
service.setMetadataCriteriaRemoveRolelessEntityDescriptors(true);
if (StringUtils.isNotBlank(sp.getSignatureLocation())) {
service.setMetadataSignatureLocation(sp.getSignatureLocation());
}
final List<String> entityIDList = determineEntityIdList(sp, resolver, service);
if (entityIDList.isEmpty()) {
LOGGER.warn("Skipped registration of [{}] since no metadata entity ids could be found", sp.getName());
return null;
}
final String entityIds = org.springframework.util.StringUtils.collectionToDelimitedString(entityIDList, "|");
service.setMetadataCriteriaDirection(PredicateFilter.Direction.INCLUDE.name());
service.setMetadataCriteriaPattern(entityIds);
LOGGER.debug("Registering saml service [{}] by entity id [{}]", sp.getName(), entityIds);
service.setServiceId(entityIds);
service.setSignAssertions(sp.isSignAssertions());
service.setSignResponses(sp.isSignResponses());
return service;
} catch (final Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private static List<String> determineEntityIdList(final AbstractSamlSPProperties sp,
final SamlRegisteredServiceCachingMetadataResolver resolver,
final SamlRegisteredService service) {
final List<String> entityIDList = sp.getEntityIds();
if (entityIDList.isEmpty()) {
final MetadataResolver metadataResolver = resolver.resolve(service);
final List<MetadataResolver> resolvers = new ArrayList<>();
if (metadataResolver instanceof ChainingMetadataResolver) {
resolvers.addAll(((ChainingMetadataResolver) metadataResolver).getResolvers());
} else {
resolvers.add(metadataResolver);
}
resolvers.forEach(r -> {
if (r instanceof AbstractBatchMetadataResolver) {
final Iterator<EntityDescriptor> it = ((AbstractBatchMetadataResolver) r).iterator();
final Optional<EntityDescriptor> descriptor =
StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.ORDERED), false)
.filter(e -> e.getSPSSODescriptor(SAMLConstants.SAML20P_NS) != null)
.findFirst();
if (descriptor.isPresent()) {
entityIDList.add(descriptor.get().getEntityID());
} else {
LOGGER.warn("Skipped registration of [{}] since no entity id could be found", sp.getName());
}
}
});
}
return entityIDList;
}
/**
* Save service only if it's not already found in the registry.
*
* @param service the service
* @param servicesManager the services manager
*/
public static void saveService(final RegisteredService service, final ServicesManager servicesManager) {
servicesManager.load();
if (servicesManager.findServiceBy(registeredService -> registeredService instanceof SamlRegisteredService
&& registeredService.getServiceId().equals(service.getServiceId())) != null) {
LOGGER.info("Service [{}] does not exist in the registry and will be added.", service.getServiceId());
servicesManager.save(service);
servicesManager.load();
} else {
LOGGER.info("Service [{}] exists in the registry and will not be added again.", service.getServiceId());
}
}
}
| Fix creating new SAML svc definitions bug on every restart (#2829)
| support/cas-server-support-saml-sp-integrations/src/main/java/org/apereo/cas/util/SamlSPUtils.java | Fix creating new SAML svc definitions bug on every restart (#2829) | <ide><path>upport/cas-server-support-saml-sp-integrations/src/main/java/org/apereo/cas/util/SamlSPUtils.java
<ide> servicesManager.load();
<ide>
<ide> if (servicesManager.findServiceBy(registeredService -> registeredService instanceof SamlRegisteredService
<del> && registeredService.getServiceId().equals(service.getServiceId())) != null) {
<add> && registeredService.getServiceId().equals(service.getServiceId())).size() == 0) {
<ide> LOGGER.info("Service [{}] does not exist in the registry and will be added.", service.getServiceId());
<ide> servicesManager.save(service);
<ide> servicesManager.load(); |
|
JavaScript | apache-2.0 | 0b99ae5807648360b4e297409abfcb4749bc8e6e | 0 | dollars0427/SQLwatcher | //Require Module
var log4js = require('log4js');
var logger = log4js.getLogger('Logging');
var mysql = require('mysql');
var mailer = require('emailjs');
var promise = require('promised-io');
var when = promise.when;
var fs = require('fs');
var settingPath = process.argv[2];
var queryListPath = process.argv[3];
if(!settingPath || !queryListPath){
printUsage();
process.exit(1);
}
function printUsage(){
var out = "Usage: " + process.argv[1] + " [Setting file] [Query list file]"
console.log(out);
}
var settingFile = JSON.parse(fs.readFileSync(settingPath));
var queryListFile = JSON.parse(fs.readFileSync(queryListPath));
var dbConfig = settingFile['database']
var queryConfig = queryListFile['query']
var timerConfig = settingFile['repeatTimer'];
var mailConfig = settingFile['mail'];
var database = require('./database');
var email = require('./email');
var mysqlOpt = {
host:dbConfig.host,
port:dbConfig.port,
user:dbConfig.username,
password:dbConfig.password,
database:dbConfig.dbName
}
var aliveMailOpt = {
text: mailConfig.alive.text,
from: mailConfig.alive.from,
to: mailConfig.alive.to,
subject: mailConfig.alive.subject
};
var warningMailOpt = {
text: mailConfig.dead.text,
from: mailConfig.dead.from,
to: mailConfig.dead.to,
subject: mailConfig.dead.subject
}
var mailConnection = mailer.server.connect({
user:mailConfig.server.user,
password:mailConfig.server.password,
host:mailConfig.server.host,
port:mailConfig.server.port,
ssl:mailConfig.server.ssl,
tls:mailConfig.server.tls
});
var workerFree = true;
var lastExecute = 0;
var times = timerConfig.ms;
setInterval(runSQL,500);
function getLock(){
if(!workerFree){
return false;
}
workerFree = false;
return true;
}
function release(reset){
if(reset){
lastExecute = new Date().getTime();
}
workerFree = true;
}
function runSQL(){
if(!getLock()){
return;
}
var now = new Date().getTime();
if (now - lastExecute < times){
release();
return;
}
var dbConnection = mysql.createConnection(mysqlOpt);
function connectDatabase(){
var p = new promise.defer();
dbConnection.connect(function(err){
if(err){
logger.error('Cannot Connect To Database!',err);
process.exit(1);
}
logger.info('Connected to database.');
p.resolve();
});
return p;
}
function _runSQL(opt){
var p = new promise.defer();
var query = queryConfig[opt["idx"]];
if(!query){
p.resolve();
return p;
}
database.excuteMySQLQuery(dbConnection,query,function(err,result){
if(err){
logger.error('Detected Error! ', err);
p.reject({
err: new Error(err),
sql: query
});
return;
}
logger.info('SQL success:', query);
p.resolve({ idx: opt["idx"] + 1});
});
return p;
}
function complete(){
var p = new promise.defer();
dbConnection.end(function(err){
if(err){
logger.error(err);
connection.end();
}
logger.info('Complete!');
release(true);
p.resolve();
});
return p;
}
function runQueries(){
var p = new promise.defer();
function runSucess(opt){
logger.warn('Run Sucess!');
p.resolve();
}
function runFailed(opt){
logger.warn('Run Failed:');
logger.warn(opt.err);
logger.warn(opt.sql);
p.resolve();
}
var funList = [];
for(var i = 0; i< queryConfig.length; i++){
funList.push(_runSQL);
}
var pSQL = promise.seq(funList, {idx: 0});
when(pSQL,runSucess,runFailed);
return p;
}
var chain = new promise.defer();
chain
.then(connectDatabase)
.then(runQueries)
.then(sendNotification)
.then(complete)
chain.resolve();
}
function sendMail(err,email){
if(err){
logger.error(err);
return;
}
logger.debug('Sended Messages: ',email);
}
| index.js | //Require Module
var log4js = require('log4js');
var logger = log4js.getLogger('Logging');
var mysql = require('mysql');
var mailer = require('emailjs');
var promise = require('promised-io');
var when = promise.when;
var fs = require('fs');
var settingPath = process.argv[2];
var queryListPath = process.argv[3];
if(!settingPath || !queryListPath){
printUsage();
process.exit(1);
}
function printUsage(){
var out = "Usage: " + process.argv[1] + " [Setting file] [Query list file]"
console.log(out);
}
var settingFile = JSON.parse(fs.readFileSync(settingPath));
var queryListFile = JSON.parse(fs.readFileSync(queryListPath));
var dbConfig = settingFile['database']
var queryConfig = queryListFile['query']
var timerConfig = settingFile['repeatTimer'];
var mailConfig = settingFile['mail'];
var database = require('./database');
var email = require('./email');
var mysqlOpt = {
host:dbConfig.host,
port:dbConfig.port,
user:dbConfig.username,
password:dbConfig.password,
database:dbConfig.dbName
}
var aliveMailOpt = {
text: mailConfig.alive.text,
from: mailConfig.alive.from,
to: mailConfig.alive.to,
subject: mailConfig.alive.subject
};
var warningMailOpt = {
text: mailConfig.dead.text,
from: mailConfig.dead.from,
to: mailConfig.dead.to,
subject: mailConfig.dead.subject
}
var mailConnection = mailer.server.connect({
user:mailConfig.server.user,
password:mailConfig.server.password,
host:mailConfig.server.host,
port:mailConfig.server.port,
ssl:mailConfig.server.ssl,
tls:mailConfig.server.tls
});
var workerFree = true;
var lastExecute = 0;
var times = timerConfig.ms;
setInterval(runSQL,500);
function getLock(){
if(!workerFree){
return false;
}
workerFree = false;
return true;
}
function release(reset){
if(reset){
lastExecute = new Date().getTime();
}
workerFree = true;
}
function runSQL(){
if(!getLock()){
return;
}
var now = new Date().getTime();
if (now - lastExecute < times){
release();
return;
}
var dbConnection = mysql.createConnection(mysqlOpt);
function connectDatabase(){
var p = new promise.defer();
dbConnection.connect(function(err){
if(err){
logger.error('Cannot Connect To Database!',err);
process.exit(1);
}
logger.info('Connected to database.');
p.resolve();
});
return p;
}
function _runSQL(opt){
var p = new promise.defer();
var query = queryConfig[opt["idx"]];
if(!query){
p.resolve();
return p;
}
database.excuteMySQLQuery(dbConnection,query,function(err,result){
if(err){
logger.error('Detected Error! ', err);
p.reject(query);
return;
}
logger.info('SQL success:', query);
p.resolve({ idx: opt["idx"] + 1});
});
return p;
}
function complete(){
var p = new promise.defer();
dbConnection.end(function(err){
if(err){
logger.error(err);
connection.end();
}
logger.info('Complete!');
release(true);
p.resolve();
});
return p;
}
function runQueries(){
var p = new promise.defer();
function runSucess(opt){
logger.warn('Run Sucess!');
p.resolve();
}
function runFailed(opt){
logger.warn('Run Failed:', opt);
p.resolve();
}
var funList = [];
for(var i = 0; i< queryConfig.length; i++){
funList.push(_runSQL);
}
var pSQL = promise.seq(funList, {idx: 0});
when(pSQL,runSucess,runFailed);
return p;
}
var chain = new promise.defer();
chain
.then(connectDatabase)
.then(runQueries)
.then(complete)
chain.resolve();
}
function sendMail(err,email){
if(err){
logger.error(err);
return;
}
logger.debug('Sended Messages: ',email);
}
| Can show error messages
| index.js | Can show error messages | <ide><path>ndex.js
<ide>
<ide> logger.error('Detected Error! ', err);
<ide>
<del> p.reject(query);
<add> p.reject({
<add> err: new Error(err),
<add> sql: query
<add> });
<ide>
<ide> return;
<ide> }
<ide>
<ide> function runFailed(opt){
<ide>
<del> logger.warn('Run Failed:', opt);
<add> logger.warn('Run Failed:');
<add> logger.warn(opt.err);
<add> logger.warn(opt.sql);
<ide>
<ide> p.resolve();
<ide>
<ide> chain
<ide> .then(connectDatabase)
<ide> .then(runQueries)
<add> .then(sendNotification)
<ide> .then(complete)
<ide>
<ide> chain.resolve(); |
|
Java | apache-2.0 | 72124d8f9eaca464dc69ce16276314558115823e | 0 | SciGaP/seagrid-rich-client,SciGaP/seagrid-rich-client,SciGaP/seagrid-rich-client | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.seagrid.desktop.ui.storage.controller;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.ImageCursor;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import org.seagrid.desktop.connectors.storage.*;
import org.seagrid.desktop.ui.commons.SEAGridDialogHelper;
import org.seagrid.desktop.ui.storage.model.FileListModel;
import org.seagrid.desktop.util.SEAGridContext;
import org.seagrid.desktop.util.messaging.SEAGridEvent;
import org.seagrid.desktop.util.messaging.SEAGridEventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Vector;
public class MassStorageBrowserController {
private final static Logger logger = LoggerFactory.getLogger(MassStorageBrowserController.class);
private static final DataFormat SERIALIZED_MIME_TYPE = new DataFormat("application/x-java-serialized-object");
@FXML
private TableView<FileListModel> fbLocalFileTable;
@FXML
private TableColumn<FileListModel,FileListModel> fbLocalFileTblFileName;
@FXML
private TableColumn<FileListModel,String> fbLocalFileTblFileSize;
@FXML
private TableColumn<FileListModel,String> fbLocalFileTblLastMod;
@FXML
private TableView<FileListModel> fbRemoteFileTable;
@FXML
private TableColumn<FileListModel,FileListModel> fbRemoteFileTblFileName;
@FXML
private TableColumn<FileListModel,String> fbRemoteFileTblFileSize;
@FXML
public TableColumn<FileListModel,String> fbRemoteFileTblLastMod;
@FXML
private TextField fbLocalPath;
@FXML
private TextField fbRemotePath;
private Path currentLocalPath;
private String currentRemotePath;
ObservableList<FileListModel> currentLocalFileList, currentRemoteFileList;
@SuppressWarnings("unused")
public void initialize(){
try{
initialiseColumnWidths();
initializeLocalFileTable();
initializeRemoteFileTable();
fbLocalPath.setAlignment(Pos.BASELINE_LEFT);
fbRemotePath.setAlignment(Pos.BASELINE_LEFT);
}catch (Exception e){
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", null,
"Failed opening mass storage browser");
if(fbLocalPath != null && fbLocalPath.getScene() != null && fbLocalPath.getScene().getWindow() != null)
((Stage)fbLocalPath.getScene().getWindow()).close();
}
}
private void initialiseColumnWidths(){
fbLocalFileTblFileName.prefWidthProperty().bind(fbLocalFileTable.widthProperty().divide(3));
fbLocalFileTblFileSize.prefWidthProperty().bind(fbLocalFileTable.widthProperty().divide(3));
fbLocalFileTblLastMod.prefWidthProperty().bind(fbLocalFileTable.widthProperty().divide(3));
fbRemoteFileTblFileName.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3));
fbRemoteFileTblFileSize.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3));
fbRemoteFileTblLastMod.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3));
}
private void initializeLocalFileTable(){
String userHome = System.getProperty("user.home");
this.currentLocalPath = Paths.get(userHome);
fbLocalFileTblFileName.setCellValueFactory(cellData-> new SimpleObjectProperty(cellData.getValue()));
fbLocalFileTblFileName.setCellFactory(param -> new TableCell<FileListModel, FileListModel>(){
@Override
public void updateItem(FileListModel item, boolean empty){
if(item != null){
HBox hBox = new HBox(2);
Image fileImage;
if(item.getFileListModelType().equals(FileListModel.FileListModelType.FILE)){
fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/file.png"));
}else{
fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/folder.png"));
}
hBox.getChildren().add(new javafx.scene.image.ImageView(fileImage));
hBox.getChildren().add(new Label(item.getFileName()));
setGraphic(hBox);
}else{
setGraphic(null);
}
}
});
fbLocalFileTblFileSize.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType()
.equals(FileListModel.FileListModelType.FILE) ? new SimpleStringProperty(cellData.getValue().getSize()+" bytes")
: null);
fbLocalFileTblFileSize.setCellFactory(param -> new TableCell<FileListModel, String>(){
@Override
public void updateItem(String item, boolean empty){
setText(item);
setAlignment(Pos.CENTER_RIGHT);
}
});
fbLocalFileTblLastMod.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType()
.equals(FileListModel.FileListModelType.PARENT_DIR) ? null
: new SimpleStringProperty(LocalDateTime.ofEpochSecond(cellData.getValue().getLastModifiedTime() / 1000, 0,
SEAGridContext.getInstance().getTimeZoneOffset()).toString()));
fbLocalFileTblLastMod.setCellFactory(param -> new TableCell<FileListModel, String>(){
@Override
public void updateItem(String item, boolean empty){
setText(item);
setAlignment(Pos.CENTER_RIGHT);
}
});
currentLocalFileList = FXCollections.observableArrayList();
fbLocalFileTable.setItems(currentLocalFileList);
fbLocalFileTable.setOnMouseClicked(event -> {
FileListModel fileListModel = fbLocalFileTable.getSelectionModel().getSelectedItem();
if(fileListModel != null && event.getClickCount()==2) {
if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)) {
currentLocalPath = Paths.get(currentLocalPath.toString() + File.separator + fileListModel.getFileName());
} else if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType
.PARENT_DIR)) {
currentLocalPath = currentLocalPath.getParent();
}
populateLocalFileList();
}
});
fbLocalFileTable.setRowFactory(tv -> {
TableRow<FileListModel> row = new TableRow<>();
row.setOnDragDetected(event -> {
if (!row.isEmpty() && !currentLocalFileList.get(row.getIndex()).getFileName().equals("..")
&& (currentLocalFileList.get(row.getIndex()).getFileListModelType().equals(FileListModel
.FileListModelType.FILE) || (currentLocalFileList.get(row.getIndex()).getFileListModelType()
.equals(FileListModel.FileListModelType.DIR)))){
FileListModel selectedFileListModel = fbLocalFileTable.getSelectionModel().getSelectedItem();
Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
db.setDragView(row.snapshot(null, null));
ClipboardContent cc = new ClipboardContent();
cc.put(SERIALIZED_MIME_TYPE, selectedFileListModel);
db.setContent(cc);
event.consume();
}
});
return row;
});
fbLocalFileTable.setOnDragOver(event -> {
fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
if (((FileListModel) db.getContent(SERIALIZED_MIME_TYPE)).getFileLocation().equals(FileListModel.FileLocation.REMOTE)) {
Image image = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/add.png"));
fbRemoteFileTable.getScene().setCursor(new ImageCursor(image));
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
event.consume();
}
}
});
fbLocalFileTable.setOnDragDropped(event -> {
fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
FileListModel draggedFileListModel = (FileListModel) db.getContent(SERIALIZED_MIME_TYPE);
if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.FILE)) {
downloadFile(draggedFileListModel.getFilePath(),
currentLocalPath.toString() + File.separator + draggedFileListModel.getFileName(), draggedFileListModel);
}else if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)){
downloadDir(draggedFileListModel.getFilePath(),
currentLocalPath.toString() + File.separator + draggedFileListModel.getFileName(), draggedFileListModel);
}
event.setDropCompleted(true);
event.consume();
}
});
populateLocalFileList();
}
private void populateLocalFileList(){
currentLocalFileList.clear();
fbLocalPath.setText(currentLocalPath.toString());
FileListModel fileListModel;
if(currentLocalPath.getParent() != null){
fileListModel = new FileListModel("..", FileListModel.FileListModelType.PARENT_DIR,0,0, FileListModel.FileLocation.LOCAL,
currentLocalPath.getParent().toString());
currentLocalFileList.add(fileListModel);
}
File parent = new File(currentLocalPath.toString());
File[] children = parent.listFiles();
for(File child : children){
if(child.getName().equals(".") || child.getName().equals("..")) continue;
fileListModel = new FileListModel(child.getName(),child.isFile() == true
? FileListModel.FileListModelType.FILE : FileListModel.FileListModelType.DIR, child.length(),
child.lastModified(), FileListModel.FileLocation.LOCAL, currentLocalPath.toString() +
File.separator + child.getName());
currentLocalFileList.add(fileListModel);
}
}
private void initializeRemoteFileTable() throws SftpException, JSchException {
this.currentRemotePath = "/";
fbRemoteFileTblFileName.setCellValueFactory(cellData-> new SimpleObjectProperty(cellData.getValue()));
fbRemoteFileTblFileName.setCellFactory(param -> new TableCell<FileListModel, FileListModel>(){
@Override
public void updateItem(FileListModel item, boolean empty){
if(item != null){
HBox hBox = new HBox(2);
Image fileImage;
if(item.getFileListModelType().equals(FileListModel.FileListModelType.FILE)){
fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/file.png"));
}else{
fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/folder.png"));
}
hBox.getChildren().add(new javafx.scene.image.ImageView(fileImage));
hBox.getChildren().add(new Label(item.getFileName()));
setGraphic(hBox);
}else{
setGraphic(null);
}
}
});
fbRemoteFileTblFileSize.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType()
.equals(FileListModel.FileListModelType.FILE) ? new SimpleStringProperty(cellData.getValue().getSize()+" bytes")
: null);
fbRemoteFileTblFileSize.setCellFactory(param -> new TableCell<FileListModel, String>(){
@Override
public void updateItem(String item, boolean empty){
setText(item);
setAlignment(Pos.CENTER_RIGHT);
}
});
fbRemoteFileTblLastMod.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType()
.equals(FileListModel.FileListModelType.PARENT_DIR) ? null
: new SimpleStringProperty(LocalDateTime.ofEpochSecond(cellData.getValue().getLastModifiedTime() / 1000, 0,
SEAGridContext.getInstance().getTimeZoneOffset()).toString()));
fbRemoteFileTblLastMod.setCellFactory(param -> new TableCell<FileListModel, String>(){
@Override
public void updateItem(String item, boolean empty){
setText(item);
setAlignment(Pos.CENTER_RIGHT);
}
});
currentRemoteFileList = FXCollections.observableArrayList();
fbRemoteFileTable.setItems(currentRemoteFileList);
fbRemoteFileTable.setOnMouseClicked(event -> {
FileListModel fileListModel = fbRemoteFileTable.getSelectionModel().getSelectedItem();
if(fileListModel != null && event.getClickCount()==2) {
if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)) {
currentRemotePath = currentRemotePath + "/" + fileListModel.getFileName();
} else if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType
.PARENT_DIR)) {
currentRemotePath = (new File(currentRemotePath)).getParent();
}
try {
populateRemoteFileTable();
} catch (Exception e) {
e.printStackTrace();
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbRemoteFileTable.getScene().getWindow(),
"Failed to load remote directory information");
}
}
});
fbRemoteFileTable.setRowFactory(tv -> {
TableRow<FileListModel> row = new TableRow<>();
row.setOnDragDetected(event -> {
if (!row.isEmpty() && !currentRemoteFileList.get(row.getIndex()).getFileName().equals("..")
&& (currentRemoteFileList.get(row.getIndex()).getFileListModelType().equals(FileListModel
.FileListModelType.FILE) || (currentRemoteFileList.get(row.getIndex()).getFileListModelType()
.equals(FileListModel.FileListModelType.DIR)))) {
FileListModel selectedFileListModel = fbRemoteFileTable.getSelectionModel().getSelectedItem();
Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
db.setDragView(row.snapshot(null, null));
ClipboardContent cc = new ClipboardContent();
cc.put(SERIALIZED_MIME_TYPE, selectedFileListModel);
db.setContent(cc);
event.consume();
}
});
return row;
});
// fbRemoteFileTable.setOnDragOver(event -> {
// fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
// Dragboard db = event.getDragboard();
// if (db.hasContent(SERIALIZED_MIME_TYPE)) {
// if (((FileListModel) db.getContent(SERIALIZED_MIME_TYPE)).getFileLocation().equals(FileListModel.FileLocation.LOCAL)) {
// Image image = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/add.png"));
// fbRemoteFileTable.getScene().setCursor(new ImageCursor(image));
// event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
// event.consume();
// }
// }
// });
// fbRemoteFileTable.setOnDragDropped(event -> {
// fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
// Dragboard db = event.getDragboard();
// if (db.hasContent(SERIALIZED_MIME_TYPE)) {
// FileListModel draggedFileListModel = (FileListModel) db.getContent(SERIALIZED_MIME_TYPE);
// if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.FILE)) {
// if ((new File(currentRemotePath)).getParent() != null && !(new File(currentRemotePath)).getParent().isEmpty()) {
// uploadFile(draggedFileListModel.getFilePath(), currentRemotePath.toString() + "/" + draggedFileListModel
// .getFileName(), draggedFileListModel);
// } else {
// uploadFile(draggedFileListModel.getFilePath(), "/" + draggedFileListModel
// .getFileName(), draggedFileListModel);
// }
// }else if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)){
// uploadDir(draggedFileListModel.getFilePath(), "/" + draggedFileListModel
// .getFileName(), draggedFileListModel);
// }
// event.setDropCompleted(true);
// event.consume();
// }
// });
populateRemoteFileTable();
}
private void populateRemoteFileTable() throws JSchException, SftpException {
currentRemoteFileList.clear();
fbRemotePath.setText(SEAGridContext.getInstance().getUserName() + currentRemotePath.toString());
FileListModel fileListModel;
if((new File(currentRemotePath)).getParent() != null && !(new File(currentRemotePath)).getParent().isEmpty()){
fileListModel = new FileListModel("..", FileListModel.FileListModelType.PARENT_DIR,0,0, FileListModel.FileLocation.REMOTE,
(new File(currentRemotePath).getParent()));
currentRemoteFileList.add(fileListModel);
}
Vector<ChannelSftp.LsEntry> children = StorageManager.getInstance().getDirectoryListing(currentRemotePath.toString());
for(ChannelSftp.LsEntry lsEntry : children){
if(lsEntry.getFilename().equals(".") || lsEntry.getFilename().equals("..")) continue;
fileListModel = new FileListModel(lsEntry.getFilename(), lsEntry.getAttrs().isDir() == false
? FileListModel.FileListModelType.FILE : FileListModel.FileListModelType.DIR, lsEntry.getAttrs().getSize(),
lsEntry.getAttrs().getATime() * 1000L, FileListModel.FileLocation.REMOTE, currentRemotePath.toString()
+ "/" + lsEntry.getFilename());
currentRemoteFileList.add(fileListModel);
}
}
private void uploadFile(String localFile, String remotePath, FileListModel upldFileModel){
Service<Boolean> service = new Service<Boolean>() {
@Override
protected Task<Boolean> createTask() {
try {
return new GuiFileUploadTask(remotePath, localFile);
} catch (Exception e) {
e.printStackTrace();
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbRemoteFileTable.getScene().getWindow(),
"Unable To Connect To File Server !");
}
return null;
}
};
SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbRemoteFileTable.getScene().getWindow(),
"Uploading File " + upldFileModel.getFileName());
service.setOnFailed((WorkerStateEvent t) -> {
SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog",
fbRemoteFileTable.getScene().getWindow(), "File Upload Failed");
});
service.setOnSucceeded((WorkerStateEvent t)->{
//removing the duplicate file with the same name
for(int i=0;i<currentRemoteFileList.size();i++){
if(currentRemoteFileList.get(i).getFileName().equals(upldFileModel.getFileName())){
currentRemoteFileList.remove(i);
}
}
upldFileModel.setFileLocation(FileListModel.FileLocation.REMOTE);
upldFileModel.setFilePath(currentRemotePath.toString()+"/"+upldFileModel.getFileName());
currentRemoteFileList.add(upldFileModel);
int dropIndex = fbRemoteFileTable.getItems().size();
fbRemoteFileTable.getSelectionModel().select(dropIndex);
SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.FILE_UPLOADED,localFile));
});
service.start();
}
private void uploadDir(String localDir, String remoteDir, FileListModel upldFileModel){
Service<Boolean> service = new Service<Boolean>() {
@Override
protected Task<Boolean> createTask() {
try {
return new GuiDirUploadTask(remoteDir, localDir);
} catch (Exception e) {
e.printStackTrace();
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbRemoteFileTable.getScene().getWindow(),
"Unable To Connect To File Server !");
}
return null;
}
};
SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbRemoteFileTable.getScene().getWindow(),
"Uploading Directory " + upldFileModel.getFileName());
service.setOnFailed((WorkerStateEvent t) -> {
SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog",
fbRemoteFileTable.getScene().getWindow(), "Directory Upload Failed");
});
service.setOnSucceeded((WorkerStateEvent t)->{
//removing the duplicate file with the same name
for(int i=0;i<currentRemoteFileList.size();i++){
if(currentRemoteFileList.get(i).getFileName().equals(upldFileModel.getFileName())){
currentRemoteFileList.remove(i);
}
}
upldFileModel.setFileLocation(FileListModel.FileLocation.REMOTE);
upldFileModel.setFilePath(currentRemotePath.toString()+"/"+upldFileModel.getFileName());
currentRemoteFileList.add(upldFileModel);
int dropIndex = fbRemoteFileTable.getItems().size();
fbRemoteFileTable.getSelectionModel().select(dropIndex);
SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.FILE_UPLOADED,localDir));
});
service.start();
}
private void downloadFile(String remoteFile, String localFile, FileListModel downFileModel){
Service<Boolean> service = new Service<Boolean>() {
@Override
protected Task<Boolean> createTask() {
try {
return new GuiFileDownloadTask(remoteFile, localFile);
} catch (Exception e) {
e.printStackTrace();
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbLocalFileTable.getScene().getWindow(),
"Unable To Connect To File Server !");
}
return null;
}
};
SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbLocalFileTable.getScene().getWindow(),
"Downloading File " + downFileModel.getFileName());
service.setOnFailed((WorkerStateEvent t) -> {
SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog",
fbLocalFileTable.getScene().getWindow(), "File Download Failed");
});
service.setOnSucceeded((WorkerStateEvent t)->{
//removing the duplicate file with the same name
for(int i=0;i<currentLocalFileList.size();i++){
if(currentLocalFileList.get(i).getFileName().equals(downFileModel.getFileName())){
currentLocalFileList.remove(i);
}
}
downFileModel.setFileLocation(FileListModel.FileLocation.LOCAL);
downFileModel.setFilePath(currentLocalPath.toString()+File.separator+downFileModel.getFileName());
currentLocalFileList.add(downFileModel);
int dropIndex = fbLocalFileTable.getItems().size();
fbLocalFileTable.getSelectionModel().select(dropIndex);
SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.FILE_DOWNLOADED,localFile));
});
service.start();
}
private void downloadDir(String remoteDir, String localDir, FileListModel downFileModel){
Service<Boolean> service = new Service<Boolean>() {
@Override
protected Task<Boolean> createTask() {
try {
return new GuiDirDownloadTask(remoteDir, localDir);
} catch (Exception e) {
e.printStackTrace();
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbLocalFileTable.getScene().getWindow(),
"Unable To Connect To File Server !");
}
return null;
}
};
SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbLocalFileTable.getScene().getWindow(),
"Downloading Directory " + downFileModel.getFileName());
service.setOnFailed((WorkerStateEvent t) -> {
SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog",
fbLocalFileTable.getScene().getWindow(), "Directory Download Failed");
});
service.setOnSucceeded((WorkerStateEvent t)->{
//removing the duplicate file with the same name
for(int i=0;i<currentLocalFileList.size();i++){
if(currentLocalFileList.get(i).getFileName().equals(downFileModel.getFileName())){
currentLocalFileList.remove(i);
}
}
downFileModel.setFileLocation(FileListModel.FileLocation.LOCAL);
downFileModel.setFilePath(currentLocalPath.toString()+File.separator+downFileModel.getFileName());
currentLocalFileList.add(downFileModel);
int dropIndex = fbLocalFileTable.getItems().size();
fbLocalFileTable.getSelectionModel().select(dropIndex);
SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.FILE_DOWNLOADED,localDir));
});
service.start();
}
public void gotoRemoteDir(String path) throws JSchException, SftpException {
currentRemoteFileList.clear();
currentRemotePath = path;
fbRemotePath.setText(SEAGridContext.getInstance().getUserName() + currentRemotePath.toString());
FileListModel fileListModel;
if((new File(currentRemotePath)).getParent() != null && !(new File(currentRemotePath)).getParent().isEmpty()){
fileListModel = new FileListModel("..", FileListModel.FileListModelType.PARENT_DIR,0,0, FileListModel.FileLocation.REMOTE,
(new File(currentRemotePath).getParent()));
currentRemoteFileList.add(fileListModel);
}
Vector<ChannelSftp.LsEntry> children = StorageManager.getInstance().getDirectoryListing(currentRemotePath.toString());
for(ChannelSftp.LsEntry lsEntry : children){
if(lsEntry.getFilename().equals(".") || lsEntry.getFilename().equals("..")) continue;
fileListModel = new FileListModel(lsEntry.getFilename(), lsEntry.getAttrs().isDir() == false
? FileListModel.FileListModelType.FILE : FileListModel.FileListModelType.DIR, lsEntry.getAttrs().getSize(),
lsEntry.getAttrs().getATime() * 1000L, FileListModel.FileLocation.REMOTE, currentRemotePath.toString()
+ "/" + lsEntry.getFilename());
currentRemoteFileList.add(fileListModel);
}
}
} | src/main/java/org/seagrid/desktop/ui/storage/controller/MassStorageBrowserController.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.seagrid.desktop.ui.storage.controller;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.ImageCursor;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import org.seagrid.desktop.connectors.storage.*;
import org.seagrid.desktop.ui.commons.SEAGridDialogHelper;
import org.seagrid.desktop.ui.storage.model.FileListModel;
import org.seagrid.desktop.util.SEAGridContext;
import org.seagrid.desktop.util.messaging.SEAGridEvent;
import org.seagrid.desktop.util.messaging.SEAGridEventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Vector;
public class MassStorageBrowserController {
private final static Logger logger = LoggerFactory.getLogger(MassStorageBrowserController.class);
private static final DataFormat SERIALIZED_MIME_TYPE = new DataFormat("application/x-java-serialized-object");
@FXML
private TableView<FileListModel> fbLocalFileTable;
@FXML
private TableColumn<FileListModel,FileListModel> fbLocalFileTblFileName;
@FXML
private TableColumn<FileListModel,String> fbLocalFileTblFileSize;
@FXML
private TableColumn<FileListModel,String> fbLocalFileTblLastMod;
@FXML
private TableView<FileListModel> fbRemoteFileTable;
@FXML
private TableColumn<FileListModel,FileListModel> fbRemoteFileTblFileName;
@FXML
private TableColumn<FileListModel,String> fbRemoteFileTblFileSize;
@FXML
public TableColumn<FileListModel,String> fbRemoteFileTblLastMod;
@FXML
private TextField fbLocalPath;
@FXML
private TextField fbRemotePath;
private Path currentLocalPath;
private String currentRemotePath;
ObservableList<FileListModel> currentLocalFileList, currentRemoteFileList;
@SuppressWarnings("unused")
public void initialize(){
try{
initialiseColumnWidths();
initializeLocalFileTable();
initializeRemoteFileTable();
fbLocalPath.setAlignment(Pos.BASELINE_LEFT);
fbRemotePath.setAlignment(Pos.BASELINE_LEFT);
}catch (Exception e){
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", null,
"Failed opening mass storage browser");
if(fbLocalPath != null && fbLocalPath.getScene() != null && fbLocalPath.getScene().getWindow() != null)
((Stage)fbLocalPath.getScene().getWindow()).close();
}
}
private void initialiseColumnWidths(){
fbLocalFileTblFileName.prefWidthProperty().bind(fbLocalFileTable.widthProperty().divide(3));
fbLocalFileTblFileSize.prefWidthProperty().bind(fbLocalFileTable.widthProperty().divide(3));
fbLocalFileTblLastMod.prefWidthProperty().bind(fbLocalFileTable.widthProperty().divide(3));
fbRemoteFileTblFileName.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3));
fbRemoteFileTblFileSize.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3));
fbRemoteFileTblLastMod.prefWidthProperty().bind(fbRemoteFileTable.widthProperty().divide(3));
}
private void initializeLocalFileTable(){
String userHome = System.getProperty("user.home");
this.currentLocalPath = Paths.get(userHome);
fbLocalFileTblFileName.setCellValueFactory(cellData-> new SimpleObjectProperty(cellData.getValue()));
fbLocalFileTblFileName.setCellFactory(param -> new TableCell<FileListModel, FileListModel>(){
@Override
public void updateItem(FileListModel item, boolean empty){
if(item != null){
HBox hBox = new HBox(2);
Image fileImage;
if(item.getFileListModelType().equals(FileListModel.FileListModelType.FILE)){
fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/file.png"));
}else{
fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/folder.png"));
}
hBox.getChildren().add(new javafx.scene.image.ImageView(fileImage));
hBox.getChildren().add(new Label(item.getFileName()));
setGraphic(hBox);
}else{
setGraphic(null);
}
}
});
fbLocalFileTblFileSize.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType()
.equals(FileListModel.FileListModelType.FILE) ? new SimpleStringProperty(cellData.getValue().getSize()+" bytes")
: null);
fbLocalFileTblFileSize.setCellFactory(param -> new TableCell<FileListModel, String>(){
@Override
public void updateItem(String item, boolean empty){
setText(item);
setAlignment(Pos.CENTER_RIGHT);
}
});
fbLocalFileTblLastMod.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType()
.equals(FileListModel.FileListModelType.PARENT_DIR) ? null
: new SimpleStringProperty(LocalDateTime.ofEpochSecond(cellData.getValue().getLastModifiedTime() / 1000, 0,
SEAGridContext.getInstance().getTimeZoneOffset()).toString()));
fbLocalFileTblLastMod.setCellFactory(param -> new TableCell<FileListModel, String>(){
@Override
public void updateItem(String item, boolean empty){
setText(item);
setAlignment(Pos.CENTER_RIGHT);
}
});
currentLocalFileList = FXCollections.observableArrayList();
fbLocalFileTable.setItems(currentLocalFileList);
fbLocalFileTable.setOnMouseClicked(event -> {
FileListModel fileListModel = fbLocalFileTable.getSelectionModel().getSelectedItem();
if(fileListModel != null && event.getClickCount()==2) {
if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)) {
currentLocalPath = Paths.get(currentLocalPath.toString() + File.separator + fileListModel.getFileName());
} else if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType
.PARENT_DIR)) {
currentLocalPath = currentLocalPath.getParent();
}
populateLocalFileList();
}
});
fbLocalFileTable.setRowFactory(tv -> {
TableRow<FileListModel> row = new TableRow<>();
row.setOnDragDetected(event -> {
if (!row.isEmpty() && !currentLocalFileList.get(row.getIndex()).getFileName().equals("..")
&& (currentLocalFileList.get(row.getIndex()).getFileListModelType().equals(FileListModel
.FileListModelType.FILE) || (currentLocalFileList.get(row.getIndex()).getFileListModelType()
.equals(FileListModel.FileListModelType.DIR)))){
FileListModel selectedFileListModel = fbLocalFileTable.getSelectionModel().getSelectedItem();
Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
db.setDragView(row.snapshot(null, null));
ClipboardContent cc = new ClipboardContent();
cc.put(SERIALIZED_MIME_TYPE, selectedFileListModel);
db.setContent(cc);
event.consume();
}
});
return row;
});
fbLocalFileTable.setOnDragOver(event -> {
fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
if (((FileListModel) db.getContent(SERIALIZED_MIME_TYPE)).getFileLocation().equals(FileListModel.FileLocation.REMOTE)) {
Image image = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/add.png"));
fbRemoteFileTable.getScene().setCursor(new ImageCursor(image));
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
event.consume();
}
}
});
fbLocalFileTable.setOnDragDropped(event -> {
fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
FileListModel draggedFileListModel = (FileListModel) db.getContent(SERIALIZED_MIME_TYPE);
if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.FILE)) {
downloadFile(draggedFileListModel.getFilePath(),
currentLocalPath.toString() + File.separator + draggedFileListModel.getFileName(), draggedFileListModel);
}else if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)){
downloadDir(draggedFileListModel.getFilePath(),
currentLocalPath.toString() + File.separator + draggedFileListModel.getFileName(), draggedFileListModel);
}
event.setDropCompleted(true);
event.consume();
}
});
populateLocalFileList();
}
private void populateLocalFileList(){
currentLocalFileList.clear();
fbLocalPath.setText(currentLocalPath.toString());
FileListModel fileListModel;
if(currentLocalPath.getParent() != null){
fileListModel = new FileListModel("..", FileListModel.FileListModelType.PARENT_DIR,0,0, FileListModel.FileLocation.LOCAL,
currentLocalPath.getParent().toString());
currentLocalFileList.add(fileListModel);
}
File parent = new File(currentLocalPath.toString());
File[] children = parent.listFiles();
for(File child : children){
if(child.getName().equals(".") || child.getName().equals("..")) continue;
fileListModel = new FileListModel(child.getName(),child.isFile() == true
? FileListModel.FileListModelType.FILE : FileListModel.FileListModelType.DIR, child.length(),
child.lastModified(), FileListModel.FileLocation.LOCAL, currentLocalPath.toString() +
File.separator + child.getName());
currentLocalFileList.add(fileListModel);
}
}
private void initializeRemoteFileTable() throws SftpException, JSchException {
this.currentRemotePath = "/";
fbRemoteFileTblFileName.setCellValueFactory(cellData-> new SimpleObjectProperty(cellData.getValue()));
fbRemoteFileTblFileName.setCellFactory(param -> new TableCell<FileListModel, FileListModel>(){
@Override
public void updateItem(FileListModel item, boolean empty){
if(item != null){
HBox hBox = new HBox(2);
Image fileImage;
if(item.getFileListModelType().equals(FileListModel.FileListModelType.FILE)){
fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/file.png"));
}else{
fileImage = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/folder.png"));
}
hBox.getChildren().add(new javafx.scene.image.ImageView(fileImage));
hBox.getChildren().add(new Label(item.getFileName()));
setGraphic(hBox);
}else{
setGraphic(null);
}
}
});
fbRemoteFileTblFileSize.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType()
.equals(FileListModel.FileListModelType.FILE) ? new SimpleStringProperty(cellData.getValue().getSize()+" bytes")
: null);
fbRemoteFileTblFileSize.setCellFactory(param -> new TableCell<FileListModel, String>(){
@Override
public void updateItem(String item, boolean empty){
setText(item);
setAlignment(Pos.CENTER_RIGHT);
}
});
fbRemoteFileTblLastMod.setCellValueFactory(cellData -> cellData.getValue().getFileListModelType()
.equals(FileListModel.FileListModelType.PARENT_DIR) ? null
: new SimpleStringProperty(LocalDateTime.ofEpochSecond(cellData.getValue().getLastModifiedTime() / 1000, 0,
SEAGridContext.getInstance().getTimeZoneOffset()).toString()));
fbRemoteFileTblLastMod.setCellFactory(param -> new TableCell<FileListModel, String>(){
@Override
public void updateItem(String item, boolean empty){
setText(item);
setAlignment(Pos.CENTER_RIGHT);
}
});
currentRemoteFileList = FXCollections.observableArrayList();
fbRemoteFileTable.setItems(currentRemoteFileList);
fbRemoteFileTable.setOnMouseClicked(event -> {
FileListModel fileListModel = fbRemoteFileTable.getSelectionModel().getSelectedItem();
if(fileListModel != null && event.getClickCount()==2) {
if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)) {
currentRemotePath = currentRemotePath + "/" + fileListModel.getFileName();
} else if (fileListModel.getFileListModelType().equals(FileListModel.FileListModelType
.PARENT_DIR)) {
currentRemotePath = (new File(currentRemotePath)).getParent();
}
try {
populateRemoteFileTable();
} catch (Exception e) {
e.printStackTrace();
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbRemoteFileTable.getScene().getWindow(),
"Failed to load remote directory information");
}
}
});
fbRemoteFileTable.setRowFactory(tv -> {
TableRow<FileListModel> row = new TableRow<>();
row.setOnDragDetected(event -> {
if (!row.isEmpty() && !currentRemoteFileList.get(row.getIndex()).getFileName().equals("..")
&& (currentRemoteFileList.get(row.getIndex()).getFileListModelType().equals(FileListModel
.FileListModelType.FILE) || (currentRemoteFileList.get(row.getIndex()).getFileListModelType()
.equals(FileListModel.FileListModelType.DIR)))) {
FileListModel selectedFileListModel = fbRemoteFileTable.getSelectionModel().getSelectedItem();
Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
db.setDragView(row.snapshot(null, null));
ClipboardContent cc = new ClipboardContent();
cc.put(SERIALIZED_MIME_TYPE, selectedFileListModel);
db.setContent(cc);
event.consume();
}
});
return row;
});
fbRemoteFileTable.setOnDragOver(event -> {
fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
if (((FileListModel) db.getContent(SERIALIZED_MIME_TYPE)).getFileLocation().equals(FileListModel.FileLocation.LOCAL)) {
Image image = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/add.png"));
fbRemoteFileTable.getScene().setCursor(new ImageCursor(image));
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
event.consume();
}
}
});
fbRemoteFileTable.setOnDragDropped(event -> {
fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
FileListModel draggedFileListModel = (FileListModel) db.getContent(SERIALIZED_MIME_TYPE);
if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.FILE)) {
if ((new File(currentRemotePath)).getParent() != null && !(new File(currentRemotePath)).getParent().isEmpty()) {
uploadFile(draggedFileListModel.getFilePath(), currentRemotePath.toString() + "/" + draggedFileListModel
.getFileName(), draggedFileListModel);
} else {
uploadFile(draggedFileListModel.getFilePath(), "/" + draggedFileListModel
.getFileName(), draggedFileListModel);
}
}else if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)){
uploadDir(draggedFileListModel.getFilePath(), "/" + draggedFileListModel
.getFileName(), draggedFileListModel);
}
event.setDropCompleted(true);
event.consume();
}
});
populateRemoteFileTable();
}
private void populateRemoteFileTable() throws JSchException, SftpException {
currentRemoteFileList.clear();
fbRemotePath.setText(SEAGridContext.getInstance().getUserName() + currentRemotePath.toString());
FileListModel fileListModel;
if((new File(currentRemotePath)).getParent() != null && !(new File(currentRemotePath)).getParent().isEmpty()){
fileListModel = new FileListModel("..", FileListModel.FileListModelType.PARENT_DIR,0,0, FileListModel.FileLocation.REMOTE,
(new File(currentRemotePath).getParent()));
currentRemoteFileList.add(fileListModel);
}
Vector<ChannelSftp.LsEntry> children = StorageManager.getInstance().getDirectoryListing(currentRemotePath.toString());
for(ChannelSftp.LsEntry lsEntry : children){
if(lsEntry.getFilename().equals(".") || lsEntry.getFilename().equals("..")) continue;
fileListModel = new FileListModel(lsEntry.getFilename(), lsEntry.getAttrs().isDir() == false
? FileListModel.FileListModelType.FILE : FileListModel.FileListModelType.DIR, lsEntry.getAttrs().getSize(),
lsEntry.getAttrs().getATime() * 1000L, FileListModel.FileLocation.REMOTE, currentRemotePath.toString()
+ "/" + lsEntry.getFilename());
currentRemoteFileList.add(fileListModel);
}
}
private void uploadFile(String localFile, String remotePath, FileListModel upldFileModel){
Service<Boolean> service = new Service<Boolean>() {
@Override
protected Task<Boolean> createTask() {
try {
return new GuiFileUploadTask(remotePath, localFile);
} catch (Exception e) {
e.printStackTrace();
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbRemoteFileTable.getScene().getWindow(),
"Unable To Connect To File Server !");
}
return null;
}
};
SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbRemoteFileTable.getScene().getWindow(),
"Uploading File " + upldFileModel.getFileName());
service.setOnFailed((WorkerStateEvent t) -> {
SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog",
fbRemoteFileTable.getScene().getWindow(), "File Upload Failed");
});
service.setOnSucceeded((WorkerStateEvent t)->{
//removing the duplicate file with the same name
for(int i=0;i<currentRemoteFileList.size();i++){
if(currentRemoteFileList.get(i).getFileName().equals(upldFileModel.getFileName())){
currentRemoteFileList.remove(i);
}
}
upldFileModel.setFileLocation(FileListModel.FileLocation.REMOTE);
upldFileModel.setFilePath(currentRemotePath.toString()+"/"+upldFileModel.getFileName());
currentRemoteFileList.add(upldFileModel);
int dropIndex = fbRemoteFileTable.getItems().size();
fbRemoteFileTable.getSelectionModel().select(dropIndex);
SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.FILE_UPLOADED,localFile));
});
service.start();
}
private void uploadDir(String localDir, String remoteDir, FileListModel upldFileModel){
Service<Boolean> service = new Service<Boolean>() {
@Override
protected Task<Boolean> createTask() {
try {
return new GuiDirUploadTask(remoteDir, localDir);
} catch (Exception e) {
e.printStackTrace();
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbRemoteFileTable.getScene().getWindow(),
"Unable To Connect To File Server !");
}
return null;
}
};
SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbRemoteFileTable.getScene().getWindow(),
"Uploading Directory " + upldFileModel.getFileName());
service.setOnFailed((WorkerStateEvent t) -> {
SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog",
fbRemoteFileTable.getScene().getWindow(), "Directory Upload Failed");
});
service.setOnSucceeded((WorkerStateEvent t)->{
//removing the duplicate file with the same name
for(int i=0;i<currentRemoteFileList.size();i++){
if(currentRemoteFileList.get(i).getFileName().equals(upldFileModel.getFileName())){
currentRemoteFileList.remove(i);
}
}
upldFileModel.setFileLocation(FileListModel.FileLocation.REMOTE);
upldFileModel.setFilePath(currentRemotePath.toString()+"/"+upldFileModel.getFileName());
currentRemoteFileList.add(upldFileModel);
int dropIndex = fbRemoteFileTable.getItems().size();
fbRemoteFileTable.getSelectionModel().select(dropIndex);
SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.FILE_UPLOADED,localDir));
});
service.start();
}
private void downloadFile(String remoteFile, String localFile, FileListModel downFileModel){
Service<Boolean> service = new Service<Boolean>() {
@Override
protected Task<Boolean> createTask() {
try {
return new GuiFileDownloadTask(remoteFile, localFile);
} catch (Exception e) {
e.printStackTrace();
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbLocalFileTable.getScene().getWindow(),
"Unable To Connect To File Server !");
}
return null;
}
};
SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbLocalFileTable.getScene().getWindow(),
"Downloading File " + downFileModel.getFileName());
service.setOnFailed((WorkerStateEvent t) -> {
SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog",
fbLocalFileTable.getScene().getWindow(), "File Download Failed");
});
service.setOnSucceeded((WorkerStateEvent t)->{
//removing the duplicate file with the same name
for(int i=0;i<currentLocalFileList.size();i++){
if(currentLocalFileList.get(i).getFileName().equals(downFileModel.getFileName())){
currentLocalFileList.remove(i);
}
}
downFileModel.setFileLocation(FileListModel.FileLocation.LOCAL);
downFileModel.setFilePath(currentLocalPath.toString()+File.separator+downFileModel.getFileName());
currentLocalFileList.add(downFileModel);
int dropIndex = fbLocalFileTable.getItems().size();
fbLocalFileTable.getSelectionModel().select(dropIndex);
SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.FILE_DOWNLOADED,localFile));
});
service.start();
}
private void downloadDir(String remoteDir, String localDir, FileListModel downFileModel){
Service<Boolean> service = new Service<Boolean>() {
@Override
protected Task<Boolean> createTask() {
try {
return new GuiDirDownloadTask(remoteDir, localDir);
} catch (Exception e) {
e.printStackTrace();
SEAGridDialogHelper.showExceptionDialogAndWait(e, "Exception Dialog", fbLocalFileTable.getScene().getWindow(),
"Unable To Connect To File Server !");
}
return null;
}
};
SEAGridDialogHelper.showProgressDialog(service, "Progress Dialog", fbLocalFileTable.getScene().getWindow(),
"Downloading Directory " + downFileModel.getFileName());
service.setOnFailed((WorkerStateEvent t) -> {
SEAGridDialogHelper.showExceptionDialogAndWait(service.getException(), "Exception Dialog",
fbLocalFileTable.getScene().getWindow(), "Directory Download Failed");
});
service.setOnSucceeded((WorkerStateEvent t)->{
//removing the duplicate file with the same name
for(int i=0;i<currentLocalFileList.size();i++){
if(currentLocalFileList.get(i).getFileName().equals(downFileModel.getFileName())){
currentLocalFileList.remove(i);
}
}
downFileModel.setFileLocation(FileListModel.FileLocation.LOCAL);
downFileModel.setFilePath(currentLocalPath.toString()+File.separator+downFileModel.getFileName());
currentLocalFileList.add(downFileModel);
int dropIndex = fbLocalFileTable.getItems().size();
fbLocalFileTable.getSelectionModel().select(dropIndex);
SEAGridEventBus.getInstance().post(new SEAGridEvent(SEAGridEvent.SEAGridEventType.FILE_DOWNLOADED,localDir));
});
service.start();
}
public void gotoRemoteDir(String path) throws JSchException, SftpException {
currentRemoteFileList.clear();
currentRemotePath = path;
fbRemotePath.setText(SEAGridContext.getInstance().getUserName() + currentRemotePath.toString());
FileListModel fileListModel;
if((new File(currentRemotePath)).getParent() != null && !(new File(currentRemotePath)).getParent().isEmpty()){
fileListModel = new FileListModel("..", FileListModel.FileListModelType.PARENT_DIR,0,0, FileListModel.FileLocation.REMOTE,
(new File(currentRemotePath).getParent()));
currentRemoteFileList.add(fileListModel);
}
Vector<ChannelSftp.LsEntry> children = StorageManager.getInstance().getDirectoryListing(currentRemotePath.toString());
for(ChannelSftp.LsEntry lsEntry : children){
if(lsEntry.getFilename().equals(".") || lsEntry.getFilename().equals("..")) continue;
fileListModel = new FileListModel(lsEntry.getFilename(), lsEntry.getAttrs().isDir() == false
? FileListModel.FileListModelType.FILE : FileListModel.FileListModelType.DIR, lsEntry.getAttrs().getSize(),
lsEntry.getAttrs().getATime() * 1000L, FileListModel.FileLocation.REMOTE, currentRemotePath.toString()
+ "/" + lsEntry.getFilename());
currentRemoteFileList.add(fileListModel);
}
}
} | disabling local to remote file transfer
| src/main/java/org/seagrid/desktop/ui/storage/controller/MassStorageBrowserController.java | disabling local to remote file transfer | <ide><path>rc/main/java/org/seagrid/desktop/ui/storage/controller/MassStorageBrowserController.java
<ide> });
<ide> return row;
<ide> });
<del> fbRemoteFileTable.setOnDragOver(event -> {
<del> fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
<del> Dragboard db = event.getDragboard();
<del> if (db.hasContent(SERIALIZED_MIME_TYPE)) {
<del> if (((FileListModel) db.getContent(SERIALIZED_MIME_TYPE)).getFileLocation().equals(FileListModel.FileLocation.LOCAL)) {
<del> Image image = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/add.png"));
<del> fbRemoteFileTable.getScene().setCursor(new ImageCursor(image));
<del> event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
<del> event.consume();
<del> }
<del> }
<del> });
<del> fbRemoteFileTable.setOnDragDropped(event -> {
<del> fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
<del> Dragboard db = event.getDragboard();
<del> if (db.hasContent(SERIALIZED_MIME_TYPE)) {
<del> FileListModel draggedFileListModel = (FileListModel) db.getContent(SERIALIZED_MIME_TYPE);
<del> if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.FILE)) {
<del> if ((new File(currentRemotePath)).getParent() != null && !(new File(currentRemotePath)).getParent().isEmpty()) {
<del> uploadFile(draggedFileListModel.getFilePath(), currentRemotePath.toString() + "/" + draggedFileListModel
<del> .getFileName(), draggedFileListModel);
<del> } else {
<del> uploadFile(draggedFileListModel.getFilePath(), "/" + draggedFileListModel
<del> .getFileName(), draggedFileListModel);
<del> }
<del> }else if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)){
<del> uploadDir(draggedFileListModel.getFilePath(), "/" + draggedFileListModel
<del> .getFileName(), draggedFileListModel);
<del> }
<del> event.setDropCompleted(true);
<del> event.consume();
<del> }
<del> });
<add>// fbRemoteFileTable.setOnDragOver(event -> {
<add>// fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
<add>// Dragboard db = event.getDragboard();
<add>// if (db.hasContent(SERIALIZED_MIME_TYPE)) {
<add>// if (((FileListModel) db.getContent(SERIALIZED_MIME_TYPE)).getFileLocation().equals(FileListModel.FileLocation.LOCAL)) {
<add>// Image image = new Image(MassStorageBrowserController.class.getResourceAsStream("/images/add.png"));
<add>// fbRemoteFileTable.getScene().setCursor(new ImageCursor(image));
<add>// event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
<add>// event.consume();
<add>// }
<add>// }
<add>// });
<add>// fbRemoteFileTable.setOnDragDropped(event -> {
<add>// fbRemoteFileTable.getScene().setCursor(Cursor.DEFAULT);
<add>// Dragboard db = event.getDragboard();
<add>// if (db.hasContent(SERIALIZED_MIME_TYPE)) {
<add>// FileListModel draggedFileListModel = (FileListModel) db.getContent(SERIALIZED_MIME_TYPE);
<add>// if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.FILE)) {
<add>// if ((new File(currentRemotePath)).getParent() != null && !(new File(currentRemotePath)).getParent().isEmpty()) {
<add>// uploadFile(draggedFileListModel.getFilePath(), currentRemotePath.toString() + "/" + draggedFileListModel
<add>// .getFileName(), draggedFileListModel);
<add>// } else {
<add>// uploadFile(draggedFileListModel.getFilePath(), "/" + draggedFileListModel
<add>// .getFileName(), draggedFileListModel);
<add>// }
<add>// }else if(draggedFileListModel.getFileListModelType().equals(FileListModel.FileListModelType.DIR)){
<add>// uploadDir(draggedFileListModel.getFilePath(), "/" + draggedFileListModel
<add>// .getFileName(), draggedFileListModel);
<add>// }
<add>// event.setDropCompleted(true);
<add>// event.consume();
<add>// }
<add>// });
<ide>
<ide> populateRemoteFileTable();
<ide> } |
|
Java | apache-2.0 | 18c4d3a042b679832eafb247ebbe00cb318a520e | 0 | CAFAudit/audit-service,CAFAudit/audit-service,CAFAudit/audit-service | /*
* Copyright 2015-2017 Hewlett Packard Enterprise Development LP.
*
* 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.hpe.caf.auditing.elastic;
import com.hpe.caf.auditing.AuditChannel;
import com.hpe.caf.auditing.AuditCoreMetadataProvider;
import com.hpe.caf.auditing.AuditEventBuilder;
import org.elasticsearch.client.transport.TransportClient;
import java.io.IOException;
public class ElasticAuditChannel implements AuditChannel {
private final TransportClient transportClient;
private final ElasticAuditIndexManager indexManager;
public ElasticAuditChannel(TransportClient transportClient, ElasticAuditIndexManager indexManager){
this.transportClient = transportClient;
this.indexManager = indexManager;
}
@Override
public void declareApplication(String applicationId) throws IOException {
// Do nothing.
}
@Override
public AuditEventBuilder createEventBuilder(AuditCoreMetadataProvider coreMetadataProvider) {
return new ElasticAuditEventBuilder(transportClient, coreMetadataProvider, indexManager);
}
@Override
public void close() throws Exception {
// Do nothing.
}
}
| caf-audit/src/main/java/com/hpe/caf/auditing/elastic/ElasticAuditChannel.java | /*
* Copyright 2015-2017 Hewlett Packard Enterprise Development LP.
*
* 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.hpe.caf.auditing.elastic;
import com.hpe.caf.auditing.AuditChannel;
import com.hpe.caf.auditing.AuditCoreMetadataProvider;
import com.hpe.caf.auditing.AuditEventBuilder;
import com.hpe.caf.auditing.internal.AuditNewEventFactory;
import org.elasticsearch.client.transport.TransportClient;
import java.io.IOException;
public class ElasticAuditChannel implements AuditChannel {
private final TransportClient transportClient;
private final ElasticAuditIndexManager indexManager;
public ElasticAuditChannel(TransportClient transportClient, ElasticAuditIndexManager indexManager){
this.transportClient = transportClient;
this.indexManager = indexManager;
}
@Override
public void declareApplication(String applicationId) throws IOException {
// Do nothing.
}
@Override
public AuditEventBuilder createEventBuilder() {
return new ElasticAuditEventBuilder(transportClient, AuditNewEventFactory.createNewEvent(), indexManager);
}
@Override
public AuditEventBuilder createEventBuilder(AuditCoreMetadataProvider coreMetadataProvider) {
return new ElasticAuditEventBuilder(transportClient, coreMetadataProvider, indexManager);
}
@Override
public void close() throws Exception {
// Do nothing.
}
}
| Removed an overload which just repeats the default implementation
| caf-audit/src/main/java/com/hpe/caf/auditing/elastic/ElasticAuditChannel.java | Removed an overload which just repeats the default implementation | <ide><path>af-audit/src/main/java/com/hpe/caf/auditing/elastic/ElasticAuditChannel.java
<ide> import com.hpe.caf.auditing.AuditChannel;
<ide> import com.hpe.caf.auditing.AuditCoreMetadataProvider;
<ide> import com.hpe.caf.auditing.AuditEventBuilder;
<del>import com.hpe.caf.auditing.internal.AuditNewEventFactory;
<ide> import org.elasticsearch.client.transport.TransportClient;
<ide>
<ide> import java.io.IOException;
<ide> }
<ide>
<ide> @Override
<del> public AuditEventBuilder createEventBuilder() {
<del> return new ElasticAuditEventBuilder(transportClient, AuditNewEventFactory.createNewEvent(), indexManager);
<del> }
<del>
<del> @Override
<ide> public AuditEventBuilder createEventBuilder(AuditCoreMetadataProvider coreMetadataProvider) {
<ide> return new ElasticAuditEventBuilder(transportClient, coreMetadataProvider, indexManager);
<ide> } |
|
Java | bsd-3-clause | eb0bca265f1894fd21e6c2470abc911ae98db757 | 0 | NCIP/cananolab,NCIP/cananolab,NCIP/cananolab | package gov.nih.nci.cananolab.dto.common;
import gov.nih.nci.cananolab.domain.common.Condition;
import gov.nih.nci.cananolab.domain.common.Datum;
import gov.nih.nci.cananolab.domain.common.File;
import gov.nih.nci.cananolab.domain.common.Finding;
import gov.nih.nci.cananolab.util.Comparators;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.DateUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* View bean for Datum
*
* @author pansu, tanq
*
*/
public class FindingBean {
private Finding domain = new Finding();
private List<Row> rows = new ArrayList<Row>();
private List<FileBean> files = new ArrayList<FileBean>();
private List<ColumnHeader> columnHeaders = new ArrayList<ColumnHeader>();
private int numberOfColumns;
private int numberOfRows;
private FileBean theFile = new FileBean();
public FindingBean() {
}
public FindingBean(Finding finding) {
domain = finding;
List<Datum> data = new ArrayList<Datum>(finding.getDatumCollection());
Collections.sort(data, new Comparators.DatumDateComparator());
if (finding.getFileCollection() != null) {
for (File file : finding.getFileCollection()) {
files.add(new FileBean(file));
}
}
Collections.sort(files, new Comparators.FileBeanDateComparator());
// get data matrix column headers in order and generate a map based on
// headers
Map<ColumnHeader, List<Datum>> datumMap = new HashMap<ColumnHeader, List<Datum>>();
Map<ColumnHeader, List<Condition>> conditionMap = new HashMap<ColumnHeader, List<Condition>>();
List<Datum> datumList = new ArrayList<Datum>();
List<Condition> conditionList = new ArrayList<Condition>();
for (Datum datum : data) {
List<Condition> conditions = new ArrayList<Condition>(datum
.getConditionCollection());
Collections.sort(conditions,
new Comparators.ConditionDateComparator());
for (Condition condition : conditions) {
ColumnHeader conditionColumn = new ColumnHeader(condition);
if (!columnHeaders.contains(conditionColumn)) {
columnHeaders.add(conditionColumn);
}
if (conditionMap.get(conditionColumn) != null) {
conditionList = conditionMap.get(conditionColumn);
} else {
conditionList = new ArrayList<Condition>();
conditionMap.put(conditionColumn, conditionList);
}
conditionList.add(condition);
}
ColumnHeader datumColumn = new ColumnHeader(datum);
if (!columnHeaders.contains(datumColumn)) {
columnHeaders.add(datumColumn);
}
if (datumMap.get(datumColumn) != null) {
datumList = datumMap.get(datumColumn);
} else {
datumList = new ArrayList<Datum>();
datumMap.put(datumColumn, datumList);
}
datumList.add(datum);
}
numberOfRows = datumMap.get(columnHeaders.get(0)).size();
numberOfColumns = columnHeaders.size();
// generate matrix
if (data != null && !data.isEmpty()) {
for (int i = 0; i < numberOfRows; i++) {
Row row = new Row();
for (int j = 0; j < numberOfColumns; j++) {
if (!conditionMap.isEmpty()) {
Condition condition = conditionMap.get(
columnHeaders.get(j)).get(0);
row.getCells().add(new TableCell(condition));
}
if (!datumMap.isEmpty()) {
Datum datum = datumMap.get(columnHeaders.get(j)).get(0);
row.getCells().add(new TableCell(datum));
}
}
rows.add(row);
}
}
}
public List<Row> getRows() {
return rows;
}
public void setRows(List<Row> rows) {
this.rows = rows;
}
public List<ColumnHeader> getColumnHeaders() {
return columnHeaders;
}
public void setColumnHeaders(List<ColumnHeader> columnHeaders) {
this.columnHeaders = columnHeaders;
}
public int getNumberOfColumns() {
return numberOfColumns;
}
public void setNumberOfColumns(int numberOfColumns) {
this.numberOfColumns = numberOfColumns;
}
public int getNumberOfRows() {
return numberOfRows;
}
public void setNumberOfRows(int numberOfRows) {
this.numberOfRows = numberOfRows;
}
public void updateMatrix(int numberOfColumns, int numberOfRows) {
this.numberOfColumns = numberOfColumns;
this.numberOfRows = numberOfRows;
List<ColumnHeader> newColumns = new ArrayList<ColumnHeader>();
if (columnHeaders.size() <= numberOfColumns) {
newColumns.addAll(columnHeaders);
for (int i = columnHeaders.size(); i < numberOfColumns; i++) {
newColumns.add(new ColumnHeader());
}
}
// remove the columnHeaders from the end
else {
for (int i = 0; i < numberOfColumns; i++) {
newColumns.add(columnHeaders.get(i));
}
}
List<Row> newRows = new ArrayList<Row>();
if (rows.size() <= numberOfRows) {
newRows.addAll(rows);
for (int i = rows.size(); i < numberOfRows; i++) {
newRows.add(new Row());
}
}
// remove the rows from the end
else {
for (int i = 0; i < numberOfRows; i++) {
newRows.add(rows.get(i));
}
}
for (int i = 0; i < numberOfRows; i++) {
Row row = newRows.get(i);
List<TableCell> cells = row.getCells();
List<TableCell> newCells = new ArrayList<TableCell>();
if (cells.size() <= numberOfColumns) {
newCells.addAll(cells);
for (int j = cells.size(); j < numberOfColumns; j++) {
newCells.add(new TableCell());
}
}
// remove the columnHeaders from the end
else {
for (int j = 0; j < numberOfColumns; j++) {
newCells.add(cells.get(i));
}
}
row.setCells(newCells);
}
columnHeaders = new ArrayList<ColumnHeader>();
columnHeaders.addAll(newColumns);
rows = new ArrayList<Row>();
rows.addAll(newRows);
}
public void removeColumn(int colIndex) {
columnHeaders.remove(colIndex);
for(int i=0; i<rows.size(); i++) {
List<TableCell>cells=rows.get(i).getCells();
cells.remove(colIndex);
}
}
public void removeRow(int rowIndex) {
rows.remove(rowIndex);
}
public void setupDomain(String createdBy) throws Exception {
int i = 0;
if (domain.getId() != null && domain.getId() <= 0) {
domain.setId(null);
}
if (domain.getId() == null
|| domain.getCreatedBy() != null
&& domain.getCreatedBy().equals(
Constants.AUTO_COPY_ANNOTATION_PREFIX)) {
domain.setCreatedBy(createdBy);
domain.setCreatedDate(new Date());
}
if (domain.getDatumCollection() != null) {
domain.getDatumCollection().clear();
} else {
domain.setDatumCollection(new HashSet<Datum>());
}
if (domain.getFileCollection() != null) {
domain.getFileCollection().clear();
} else {
domain.setFileCollection(new HashSet<File>());
}
int j = 0;
for (FileBean file : files) {
domain.getFileCollection().add(file.getDomainFile());
j++;
}
for (Row row : rows) {
int cInd = 0;
List<Condition> rowConditions = new ArrayList<Condition>();
List<Datum> rowData = new ArrayList<Datum>();
for (TableCell cell : row.getCells()) {
ColumnHeader columnHeader = columnHeaders.get(cInd);
if (cell.getDatumOrCondition().equals("Datum")) {
Datum datum = cell.getDatum();
datum.setValue(cell.getValue());
datum.setValueType(columnHeader.getValueType());
datum.setValueUnit(columnHeader.getValueUnit());
datum.setName(columnHeader.getColumnName());
rowData.add(datum);
} else if (cell.getDatumOrCondition().equals("Condition")) {
Condition condition = cell.getCondition();
condition.setValue(cell.getValue());
condition.setValueType(columnHeader.getValueType());
condition.setValueUnit(columnHeader.getValueUnit());
condition.setName(columnHeader.getColumnName());
condition.setProperty(columnHeader.getConditionProperty());
rowConditions.add(condition);
}
cInd++;
}
// associate conditions to each datum on each row
for (Datum datum : rowData) {
if (datum.getId() != null && datum.getId() <= 0) {
datum.setId(null);
}
// if new
if (datum.getId() == null) {
datum.setCreatedBy(createdBy);
datum.setCreatedDate(DateUtils.addSecondsToCurrentDate(i));
}
if (datum.getConditionCollection() == null) {
datum.setConditionCollection(new HashSet<Condition>());
} else {
datum.getConditionCollection().clear();
}
for (Condition condition : rowConditions) {
if (condition.getId() != null && condition.getId() <= 0) {
condition.setId(null);
}
// if new
if (condition.getId() == null) {
condition.setCreatedBy(createdBy);
condition.setCreatedDate(DateUtils
.addSecondsToCurrentDate(i));
}
datum.getConditionCollection().add(condition);
}
domain.getDatumCollection().add(datum);
datum.setFinding(domain);
i++;
}
}
}
/**
* Compares <code>obj</code> to it self and returns true if they both are
* same
*
* @param obj
*/
public boolean equals(Object obj) {
if (obj instanceof FindingBean) {
FindingBean findingBean = (FindingBean) obj;
if (domain.getId() != null
&& domain.getId().equals(findingBean.getDomain().getId()))
return true;
}
return false;
}
/**
* Returns hash code for the primary key of the object
*/
public int hashCode() {
if (getDomain().getId() != null)
return getDomain().getId().hashCode();
return 0;
}
public FileBean getTheFile() {
return theFile;
}
public void setTheFile(FileBean theFile) {
this.theFile = theFile;
}
public List<FileBean> getFiles() {
return files;
}
public void setFiles(List<FileBean> files) {
this.files = files;
}
public Finding getDomain() {
return domain;
}
public void addFile(FileBean file) {
if (files.contains(file)) {
files.remove(file);
}
files.add(file);
}
public void removeFile(FileBean file) {
files.remove(file);
}
}
| src/gov/nih/nci/cananolab/dto/common/FindingBean.java | package gov.nih.nci.cananolab.dto.common;
import gov.nih.nci.cananolab.domain.common.Condition;
import gov.nih.nci.cananolab.domain.common.Datum;
import gov.nih.nci.cananolab.domain.common.File;
import gov.nih.nci.cananolab.domain.common.Finding;
import gov.nih.nci.cananolab.util.Comparators;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.DateUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* View bean for Datum
*
* @author pansu, tanq
*
*/
public class FindingBean {
private Finding domain = new Finding();
private List<Row> rows = new ArrayList<Row>();
private List<FileBean> files = new ArrayList<FileBean>();
private List<ColumnHeader> columnHeaders = new ArrayList<ColumnHeader>();
private int numberOfColumns;
private int numberOfRows;
private FileBean theFile = new FileBean();
public FindingBean() {
}
public FindingBean(Finding finding) {
domain = finding;
List<Datum> data = new ArrayList<Datum>(finding.getDatumCollection());
Collections.sort(data, new Comparators.DatumDateComparator());
if (finding.getFileCollection() != null) {
for (File file : finding.getFileCollection()) {
files.add(new FileBean(file));
}
}
Collections.sort(files, new Comparators.FileBeanDateComparator());
// get data matrix column headers in order and generate a map based on
// headers
Map<ColumnHeader, List<Datum>> datumMap = new HashMap<ColumnHeader, List<Datum>>();
Map<ColumnHeader, List<Condition>> conditionMap = new HashMap<ColumnHeader, List<Condition>>();
List<Datum> datumList = new ArrayList<Datum>();
List<Condition> conditionList = new ArrayList<Condition>();
for (Datum datum : data) {
List<Condition> conditions = new ArrayList<Condition>(datum
.getConditionCollection());
Collections.sort(conditions,
new Comparators.ConditionDateComparator());
for (Condition condition : conditions) {
ColumnHeader conditionColumn = new ColumnHeader(condition);
if (!columnHeaders.contains(conditionColumn)) {
columnHeaders.add(conditionColumn);
}
if (conditionMap.get(conditionColumn) != null) {
conditionList = conditionMap.get(conditionColumn);
} else {
conditionList = new ArrayList<Condition>();
conditionMap.put(conditionColumn, conditionList);
}
conditionList.add(condition);
}
ColumnHeader datumColumn = new ColumnHeader(datum);
if (!columnHeaders.contains(datumColumn)) {
columnHeaders.add(datumColumn);
}
if (datumMap.get(datumColumn) != null) {
datumList = datumMap.get(datumColumn);
} else {
datumList = new ArrayList<Datum>();
datumMap.put(datumColumn, datumList);
}
datumList.add(datum);
}
numberOfRows = datumMap.get(columnHeaders.get(0)).size();
numberOfColumns = columnHeaders.size();
// generate matrix
if (data != null && !data.isEmpty()) {
for (int i = 0; i < numberOfRows; i++) {
Row row = new Row();
for (int j = 0; j < numberOfColumns; j++) {
if (!conditionMap.isEmpty()) {
Condition condition = conditionMap.get(
columnHeaders.get(j)).get(0);
row.getCells().add(new TableCell(condition));
}
if (!datumMap.isEmpty()) {
Datum datum = datumMap.get(columnHeaders.get(j)).get(0);
row.getCells().add(new TableCell(datum));
}
}
rows.add(row);
}
}
}
public List<Row> getRows() {
return rows;
}
public void setRows(List<Row> rows) {
this.rows = rows;
}
public List<ColumnHeader> getColumnHeaders() {
return columnHeaders;
}
public void setColumnHeaders(List<ColumnHeader> columnHeaders) {
this.columnHeaders = columnHeaders;
}
public int getNumberOfColumns() {
return numberOfColumns;
}
public void setNumberOfColumns(int numberOfColumns) {
this.numberOfColumns = numberOfColumns;
}
public int getNumberOfRows() {
return numberOfRows;
}
public void setNumberOfRows(int numberOfRows) {
this.numberOfRows = numberOfRows;
}
public void updateMatrix(int numberOfColumns, int numberOfRows) {
this.numberOfColumns = numberOfColumns;
this.numberOfRows = numberOfRows;
List<ColumnHeader> newColumns = new ArrayList<ColumnHeader>();
if (columnHeaders.size() <= numberOfColumns) {
newColumns.addAll(columnHeaders);
for (int i = columnHeaders.size(); i < numberOfColumns; i++) {
newColumns.add(new ColumnHeader());
}
}
// remove the columnHeaders from the end
else {
for (int i = 0; i < numberOfColumns; i++) {
newColumns.add(columnHeaders.get(i));
}
}
List<Row> newRows = new ArrayList<Row>();
if (rows.size() <= numberOfRows) {
newRows.addAll(rows);
for (int i = rows.size(); i < numberOfRows; i++) {
newRows.add(new Row());
}
}
// remove the rows from the end
else {
for (int i = 0; i < numberOfRows; i++) {
newRows.add(rows.get(i));
}
}
for (int i = 0; i < numberOfRows; i++) {
Row row = newRows.get(i);
List<TableCell> cells = row.getCells();
List<TableCell> newCells = new ArrayList<TableCell>();
if (cells.size() <= numberOfColumns) {
newCells.addAll(cells);
for (int j = cells.size(); j < numberOfColumns; j++) {
newCells.add(new TableCell());
}
}
// remove the columnHeaders from the end
else {
for (int j = 0; j < numberOfColumns; j++) {
newCells.add(cells.get(i));
}
}
row.setCells(newCells);
}
columnHeaders = new ArrayList<ColumnHeader>();
columnHeaders.addAll(newColumns);
rows = new ArrayList<Row>();
rows.addAll(newRows);
}
public void setupDomain(String createdBy) throws Exception {
int i = 0;
if (domain.getId() != null && domain.getId() <= 0) {
domain.setId(null);
}
if (domain.getId() == null
|| domain.getCreatedBy() != null
&& domain.getCreatedBy().equals(
Constants.AUTO_COPY_ANNOTATION_PREFIX)) {
domain.setCreatedBy(createdBy);
domain.setCreatedDate(new Date());
}
if (domain.getDatumCollection() != null) {
domain.getDatumCollection().clear();
} else {
domain.setDatumCollection(new HashSet<Datum>());
}
if (domain.getFileCollection() != null) {
domain.getFileCollection().clear();
} else {
domain.setFileCollection(new HashSet<File>());
}
int j = 0;
for (FileBean file : files) {
domain.getFileCollection().add(file.getDomainFile());
j++;
}
for (Row row : rows) {
int cInd = 0;
List<Condition> rowConditions = new ArrayList<Condition>();
List<Datum> rowData = new ArrayList<Datum>();
for (TableCell cell : row.getCells()) {
ColumnHeader columnHeader = columnHeaders.get(cInd);
if (cell.getDatumOrCondition().equals("Datum")) {
Datum datum = cell.getDatum();
datum.setValue(cell.getValue());
datum.setValueType(columnHeader.getValueType());
datum.setValueUnit(columnHeader.getValueUnit());
datum.setName(columnHeader.getColumnName());
rowData.add(datum);
} else if (cell.getDatumOrCondition().equals("Condition")) {
Condition condition = cell.getCondition();
condition.setValue(cell.getValue());
condition.setValueType(columnHeader.getValueType());
condition.setValueUnit(columnHeader.getValueUnit());
condition.setName(columnHeader.getColumnName());
condition.setProperty(columnHeader.getConditionProperty());
rowConditions.add(condition);
}
cInd++;
}
// associate conditions to each datum on each row
for (Datum datum : rowData) {
if (datum.getId() != null && datum.getId() <= 0) {
datum.setId(null);
}
// if new
if (datum.getId() == null) {
datum.setCreatedBy(createdBy);
datum.setCreatedDate(DateUtils.addSecondsToCurrentDate(i));
}
if (datum.getConditionCollection() == null) {
datum.setConditionCollection(new HashSet<Condition>());
} else {
datum.getConditionCollection().clear();
}
for (Condition condition : rowConditions) {
if (condition.getId() != null && condition.getId() <= 0) {
condition.setId(null);
}
// if new
if (condition.getId() == null) {
condition.setCreatedBy(createdBy);
condition.setCreatedDate(DateUtils
.addSecondsToCurrentDate(i));
}
datum.getConditionCollection().add(condition);
}
domain.getDatumCollection().add(datum);
datum.setFinding(domain);
i++;
}
}
}
/**
* Compares <code>obj</code> to it self and returns true if they both are
* same
*
* @param obj
*/
public boolean equals(Object obj) {
if (obj instanceof FindingBean) {
FindingBean findingBean = (FindingBean) obj;
if (domain.getId() != null
&& domain.getId().equals(findingBean.getDomain().getId()))
return true;
}
return false;
}
/**
* Returns hash code for the primary key of the object
*/
public int hashCode() {
if (getDomain().getId() != null)
return getDomain().getId().hashCode();
return 0;
}
public FileBean getTheFile() {
return theFile;
}
public void setTheFile(FileBean theFile) {
this.theFile = theFile;
}
public List<FileBean> getFiles() {
return files;
}
public void setFiles(List<FileBean> files) {
this.files = files;
}
public Finding getDomain() {
return domain;
}
public void addFile(FileBean file) {
if (files.contains(file)) {
files.remove(file);
}
files.add(file);
}
public void removeFile(FileBean file) {
files.remove(file);
}
}
| added removeColumn and removeRow
SVN-Revision: 15073
| src/gov/nih/nci/cananolab/dto/common/FindingBean.java | added removeColumn and removeRow | <ide><path>rc/gov/nih/nci/cananolab/dto/common/FindingBean.java
<ide> columnHeaders.addAll(newColumns);
<ide> rows = new ArrayList<Row>();
<ide> rows.addAll(newRows);
<add> }
<add>
<add> public void removeColumn(int colIndex) {
<add> columnHeaders.remove(colIndex);
<add> for(int i=0; i<rows.size(); i++) {
<add> List<TableCell>cells=rows.get(i).getCells();
<add> cells.remove(colIndex);
<add> }
<add> }
<add>
<add> public void removeRow(int rowIndex) {
<add> rows.remove(rowIndex);
<ide> }
<ide>
<ide> public void setupDomain(String createdBy) throws Exception { |
|
Java | apache-2.0 | 2cca9bd3cee3f7d3b88f165c39234823d51358ee | 0 | signed/intellij-community,hurricup/intellij-community,ibinti/intellij-community,asedunov/intellij-community,FHannes/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,allotria/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,semonte/intellij-community,semonte/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,da1z/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,signed/intellij-community,ibinti/intellij-community,apixandru/intellij-community,signed/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,signed/intellij-community,fitermay/intellij-community,xfournet/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,signed/intellij-community,hurricup/intellij-community,signed/intellij-community,allotria/intellij-community,xfournet/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,semonte/intellij-community,fitermay/intellij-community,da1z/intellij-community,asedunov/intellij-community,apixandru/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,da1z/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,semonte/intellij-community,xfournet/intellij-community,FHannes/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,apixandru/intellij-community,asedunov/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,signed/intellij-community,hurricup/intellij-community,hurricup/intellij-community,asedunov/intellij-community,semonte/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,da1z/intellij-community,hurricup/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,signed/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,signed/intellij-community,vvv1559/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,semonte/intellij-community,asedunov/intellij-community,apixandru/intellij-community,fitermay/intellij-community,da1z/intellij-community,ibinti/intellij-community,hurricup/intellij-community,apixandru/intellij-community,asedunov/intellij-community,semonte/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,signed/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,allotria/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,signed/intellij-community,fitermay/intellij-community,semonte/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,asedunov/intellij-community,semonte/intellij-community | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeHighlighting;
public interface Pass {
int UPDATE_FOLDING = 1;
int POPUP_HINTS = 3;
int UPDATE_ALL = 4;
/** will be removed shortly; use {@link #LINE_MARKERS} instead*/
@Deprecated
int UPDATE_OVERRIDDEN_MARKERS = 6;
int LOCAL_INSPECTIONS = 7;
int EXTERNAL_TOOLS = 8;
int WOLF = 9;
int LINE_MARKERS = 11;
int WHOLE_FILE_LOCAL_INSPECTIONS = 12;
int LAST_PASS = WHOLE_FILE_LOCAL_INSPECTIONS;
} | platform/analysis-impl/src/com/intellij/codeHighlighting/Pass.java | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeHighlighting;
public interface Pass {
int UPDATE_FOLDING = 1;
int POPUP_HINTS = 3;
int UPDATE_ALL = 4;
int LOCAL_INSPECTIONS = 7;
int EXTERNAL_TOOLS = 8;
int WOLF = 9;
int LINE_MARKERS = 11;
int WHOLE_FILE_LOCAL_INSPECTIONS = 12;
int LAST_PASS = WHOLE_FILE_LOCAL_INSPECTIONS;
} | added constatnt back temporarily for compatibility
| platform/analysis-impl/src/com/intellij/codeHighlighting/Pass.java | added constatnt back temporarily for compatibility | <ide><path>latform/analysis-impl/src/com/intellij/codeHighlighting/Pass.java
<ide> int UPDATE_FOLDING = 1;
<ide> int POPUP_HINTS = 3;
<ide> int UPDATE_ALL = 4;
<add> /** will be removed shortly; use {@link #LINE_MARKERS} instead*/
<add> @Deprecated
<add> int UPDATE_OVERRIDDEN_MARKERS = 6;
<ide> int LOCAL_INSPECTIONS = 7;
<ide> int EXTERNAL_TOOLS = 8;
<ide> int WOLF = 9; |
|
JavaScript | mit | ee9a6ac0c34bb28070f1447355b3c043fa54f410 | 0 | anthony-benavente/agora-site-front-end,anthony-benavente/agora-site-front-end,anthony-benavente/agora-site-front-end | 'use strict';
angular.module('angularRestfulAuth')
.controller('HomeCtrl', ['$rootScope', '$scope', '$location', '$localStorage', 'Main', function($rootScope, $scope, $location, $localStorage, Main) {
$scope.signin = function() {
var formData = {
username: $scope.username,
password: $scope.password
}
Main.signin(formData, function(res) {
if (res.type == false) {
alert(res.data);
} else {
$localStorage.token = res.data.token;
Main.changeUser(Main.getUserFromToken($localStorage.token));
window.location = '/#/preview';
}
}, function() {
$rootScope.error = 'Failed to signin';
});
};
$scope.register = function() {
var formData = {
name: $scope.name,
username: $scope.username,
password: $scope.password,
email: $scope.email
};
if ($scope.password === $scope.confirmPassword) {
Main.register(formData, function(res) {
if (res.type == false) {
alert(res.data);
} else {
$localStorage.token = res.data.token;
window.location = '/';
}
}, function() {
$rootScope.error = 'Failed to register';
});
} else {
$scope.passwordWarning = "Passwords do not match";
}
};
$scope.me = function() {
Main.me(function(res){
$scope.myDetails = res;
}, function() {
$rootScope.error = 'Failed to fetch details';
});
};
$scope.logout = function() {
Main.logout(function() {
window.location = '/';
}, function() {
alert('Failed to logout');
});
};
$scope.token = $localStorage.token;
}])
.controller('AgoraPreviewCtrl', ['$rootScope', '$scope', '$location', '$localStorage', 'Main',
function($rootScope, $scope, $location, $localStorage, Main) {
function setSelected(arr, selected) {
for (var i = 0; i < arr.length; i++) {
arr[i] = selected == i;
}
}
// if ($rootScope.)
var currentUser = Main.getUserFromToken($localStorage.token);
$scope.currentUser = currentUser;
if (typeof currentUser !== 'undefined') {
var pageContent = '/partials/agora';
var focus = [true, false, false, false, false];
if (window.location.href.indexOf('about') > -1) {
pageContent += '/about.html';
setSelected(focus, 4);
$scope.canEdit = true;
} else if (window.location.href.indexOf('contact') > -1) {
pageContent += '/contact.html';
setSelected(focus, 3);
$scope.canEdit = true;
} else if (window.location.href.indexOf('resume') > -1) {
pageContent += '/resume.html';
setSelected(focus, 2);
$scope.canEdit = true;
} else if (window.location.href.indexOf('portfolio') > -1) {
pageContent += '/portfolio.html';
setSelected(focus, 1);
$scope.canEdit = false;
} else {
pageContent += '/home.html';
setSelected(focus, 0);
$scope.canEdit = true;
}
$scope.pageContent = pageContent;
$scope.focus = focus;
} else {
window.location = '/#/signin';
}
}])
.controller('MeCtrl', ['$rootScope', '$scope', '$location', '$localStorage', 'Main',
function($rootScope, $scope, $location, $localStorage, Main) {
$scope.currentUser = Main.getUserFromToken($localStorage.token);
}]);
| app/scripts/controllers.js | 'use strict';
angular.module('angularRestfulAuth')
.controller('HomeCtrl', ['$rootScope', '$scope', '$location', '$localStorage', 'Main', function($rootScope, $scope, $location, $localStorage, Main) {
$scope.signin = function() {
var formData = {
username: $scope.username,
password: $scope.password
}
Main.signin(formData, function(res) {
if (res.type == false) {
alert(res.data);
} else {
Main.changeUser(Main.getUserFromToken($localStorage.token));
window.location = '/#/preview';
}
}, function() {
$rootScope.error = 'Failed to signin';
});
};
$scope.register = function() {
var formData = {
name: $scope.name,
username: $scope.username,
password: $scope.password,
email: $scope.email
};
if ($scope.password === $scope.confirmPassword) {
Main.register(formData, function(res) {
if (res.type == false) {
alert(res.data);
} else {
$localStorage.token = res.data.token;
window.location = '/';
}
}, function() {
$rootScope.error = 'Failed to register';
});
} else {
$scope.passwordWarning = "Passwords do not match";
}
};
$scope.me = function() {
Main.me(function(res){
$scope.myDetails = res;
}, function() {
$rootScope.error = 'Failed to fetch details';
});
};
$scope.logout = function() {
Main.logout(function() {
window.location = '/';
}, function() {
alert('Failed to logout');
});
};
$scope.token = $localStorage.token;
}])
.controller('AgoraPreviewCtrl', ['$rootScope', '$scope', '$location', '$localStorage', 'Main',
function($rootScope, $scope, $location, $localStorage, Main) {
function setSelected(arr, selected) {
for (var i = 0; i < arr.length; i++) {
arr[i] = selected == i;
}
}
// if ($rootScope.)
var currentUser = Main.getUserFromToken($localStorage.token);
$scope.currentUser = currentUser;
if (typeof currentUser !== 'undefined') {
var pageContent = '/partials/agora';
var focus = [true, false, false, false, false];
if (window.location.href.indexOf('about') > -1) {
pageContent += '/about.html';
setSelected(focus, 4);
$scope.canEdit = true;
} else if (window.location.href.indexOf('contact') > -1) {
pageContent += '/contact.html';
setSelected(focus, 3);
$scope.canEdit = true;
} else if (window.location.href.indexOf('resume') > -1) {
pageContent += '/resume.html';
setSelected(focus, 2);
$scope.canEdit = true;
} else if (window.location.href.indexOf('portfolio') > -1) {
pageContent += '/portfolio.html';
setSelected(focus, 1);
$scope.canEdit = false;
} else {
pageContent += '/home.html';
setSelected(focus, 0);
$scope.canEdit = true;
}
$scope.pageContent = pageContent;
$scope.focus = focus;
} else {
window.location = '/#/signin';
}
}])
.controller('MeCtrl', ['$rootScope', '$scope', '$location', '$localStorage', 'Main',
function($rootScope, $scope, $location, $localStorage, Main) {
$scope.currentUser = Main.getUserFromToken($localStorage.token);
}]);
| Fixed token not updating after sign in
| app/scripts/controllers.js | Fixed token not updating after sign in | <ide><path>pp/scripts/controllers.js
<ide> if (res.type == false) {
<ide> alert(res.data);
<ide> } else {
<add> $localStorage.token = res.data.token;
<ide> Main.changeUser(Main.getUserFromToken($localStorage.token));
<ide> window.location = '/#/preview';
<ide> } |
|
Java | apache-2.0 | af5aeaa3141b290e92327ff9978633547e662097 | 0 | cwenao/DSAA | /**
* Company
* Copyright (C) 2014-2017 All Rights Reserved.
*/
package com.cwenao.trying.linkedlist;
/**
* @author cwenao
* @version $Id DoublyLinkedList.java, v 0.1 2017-12-28 07:34 cwenao Exp $$
*/
public class DoublyLinkedList {
Node head;
class Node{
int data;
Node pre;
Node next;
Node(int data) {
this.data = data;
}
}
public void push(int data) {
Node addNode = new Node(data);
addNode.next = head;
addNode.pre = null;
if (head !=null) {
head.pre = addNode;
}
head = addNode;
}
public void insertAfter(Node current, int data) {
Node newNode = new Node(data);
Node currentNextNode = current.next;
current.next = newNode;
newNode.next = currentNextNode;
newNode.pre = current;
if (currentNextNode!=null) {
currentNextNode.pre = newNode;
}
}
public void deleteNodeWithKey(int key) {
Node tmp = head;
Node pre = null;
if (tmp != null && tmp.data == key) {
head = tmp.next;
return;
}
while (tmp != null && tmp.data != key) {
pre = tmp;
tmp = tmp.next;
}
if (tmp == null) {
return;
}
pre.next = tmp.next;
}
public void deleteNodeWithPosition(int position) {
if (head == null) {
return;
}
Node tmp = head;
if (position == 0) {
head = tmp.next;
return;
}
for (int i = 0; i<position -1;i++) {
tmp = tmp.next;
}
if (tmp == null || tmp.next == null) {
return;
}
tmp.next = tmp.next.next;
}
}
| data-structure/src/main/java/com/cwenao/trying/linkedlist/DoublyLinkedList.java | /**
* Company
* Copyright (C) 2014-2017 All Rights Reserved.
*/
package com.cwenao.trying.linkedlist;
/**
* @author cwenao
* @version $Id DoublyLinkedList.java, v 0.1 2017-12-28 07:34 cwenao Exp $$
*/
public class DoublyLinkedList {
Node head;
class Node{
int data;
Node pre;
Node next;
Node(int data) {
this.data = data;
}
}
public void push(int data) {
Node addNode = new Node(data);
addNode.next = head;
addNode.pre = null;
if (head !=null) {
head.pre = addNode;
}
head = addNode;
}
public void insertAfter(Node current, int data) {
Node newNode = new Node(data);
Node currentNextNode = current.next;
current.next = newNode;
newNode.next = currentNextNode;
newNode.pre = current;
if (currentNextNode!=null) {
currentNextNode.pre = newNode;
}
}
}
| update
| data-structure/src/main/java/com/cwenao/trying/linkedlist/DoublyLinkedList.java | update | <ide><path>ata-structure/src/main/java/com/cwenao/trying/linkedlist/DoublyLinkedList.java
<ide> }
<ide> }
<ide>
<add> public void deleteNodeWithKey(int key) {
<add> Node tmp = head;
<add> Node pre = null;
<add> if (tmp != null && tmp.data == key) {
<add> head = tmp.next;
<add> return;
<add> }
<add>
<add> while (tmp != null && tmp.data != key) {
<add> pre = tmp;
<add> tmp = tmp.next;
<add> }
<add>
<add> if (tmp == null) {
<add> return;
<add> }
<add>
<add> pre.next = tmp.next;
<add> }
<add>
<add> public void deleteNodeWithPosition(int position) {
<add>
<add> if (head == null) {
<add> return;
<add> }
<add> Node tmp = head;
<add>
<add> if (position == 0) {
<add> head = tmp.next;
<add> return;
<add> }
<add>
<add> for (int i = 0; i<position -1;i++) {
<add> tmp = tmp.next;
<add> }
<add>
<add> if (tmp == null || tmp.next == null) {
<add> return;
<add> }
<add>
<add> tmp.next = tmp.next.next;
<add> }
<add>
<ide> } |
|
Java | lgpl-2.1 | 4c53a2f3d35f5100c45d89e9160c63cc98b85ea6 | 0 | xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.container.servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.xwiki.component.embed.EmbeddableComponentManager;
import org.xwiki.component.internal.StackingComponentEventManager;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.container.ApplicationContextListenerManager;
import org.xwiki.container.Container;
import org.xwiki.environment.Environment;
import org.xwiki.environment.internal.ServletEnvironment;
import org.xwiki.observation.ObservationManager;
import org.xwiki.observation.event.ApplicationStartedEvent;
import org.xwiki.observation.event.ApplicationStoppedEvent;
/**
* Implementation of the {@link ServletContextListener}. Initializes component manager and application context.
*
* @version $Id$
*/
public class XWikiServletContextListener implements ServletContextListener
{
/** The component manager used to lookup other components. */
private EmbeddableComponentManager componentManager;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent)
{
// Initializes the Embeddable Component Manager
EmbeddableComponentManager ecm = new EmbeddableComponentManager();
// Initialize all the components. Note that this can fail with a Runtime Exception. This is done voluntarily so
// that the XWiki webaopp will not be available if one component fails to load. It's better to fail-fast.
ecm.initialize(this.getClass().getClassLoader());
this.componentManager = ecm;
// This is a temporary bridge to allow non XWiki components to lookup XWiki components.
// We're putting the XWiki Component Manager instance in the Servlet Context so that it's
// available in the XWikiAction class which in turn puts it into the XWikiContext instance.
// Class that need to lookup then just need to get it from the XWikiContext instance.
// This is of course not necessary for XWiki components since they just need to implement
// the Composable interface to get access to the Component Manager or better they simply
// need to declare their components requirements using the @Inject annotation of the xwiki
// component manager together with a private class member, for automatic injection by the CM on init.
servletContextEvent.getServletContext().setAttribute(
org.xwiki.component.manager.ComponentManager.class.getName(), this.componentManager);
// Use a Component Event Manager that stacks Component instance creation events till we tell it to flush them.
// The reason is that the Observation Manager used to send the events but we need the Application Context to
// be set up before we start sending events since there can be Observation Listener components that require
// the Application Context (this is the case for example for the Office Importer Lifecycle Listener).
StackingComponentEventManager eventManager = new StackingComponentEventManager();
this.componentManager.setComponentEventManager(eventManager);
// Initialize the Environment
try {
ServletEnvironment servletEnvironment = this.componentManager.getInstance(Environment.class);
servletEnvironment.setServletContext(servletContextEvent.getServletContext());
} catch (ComponentLookupException e) {
throw new RuntimeException("Failed to initialize the Servlet Environment", e);
}
// Initializes the Application Context.
// Even though the notion of ApplicationContext has been deprecated in favor of the notion of Environment we
// still keep this initialization for backward-compatibility.
// TODO: Add an Observation Even that we send when the Environment is initialized so that we can move the code
// below in an Event Listener and move it to the legacy module.
try {
ServletContainerInitializer containerInitializer =
this.componentManager.getInstance(ServletContainerInitializer.class);
containerInitializer.initializeApplicationContext(servletContextEvent.getServletContext());
} catch (ComponentLookupException e) {
throw new RuntimeException("Failed to initialize the Application Context", e);
}
// Send an Observation event to signal the XWiki application is started. This allows components who need to do
// something on startup to do it.
ObservationManager observationManager;
try {
observationManager = this.componentManager.getInstance(ObservationManager.class);
} catch (ComponentLookupException e) {
throw new RuntimeException("Failed to find the Observation Manager component", e);
}
// Now that the Application Context is set up, send the Component instance creation events we had stacked up.
eventManager.setObservationManager(observationManager);
eventManager.shouldStack(false);
eventManager.flushEvents();
// Indicate to the various components that XWiki is ready
observationManager.notify(new ApplicationStartedEvent(), this);
}
@Override
public void contextDestroyed(ServletContextEvent sce)
{
// It's possible that the Component Manager failed to initialize some of the required components.
if (this.componentManager != null) {
// Send an Observation event to signal the XWiki application is stopped. This allows components who need
// to do something on stop to do it.
try {
ObservationManager observationManager = this.componentManager.getInstance(ObservationManager.class);
observationManager.notify(new ApplicationStoppedEvent(), this);
} catch (ComponentLookupException e) {
// Nothing to do here.
// TODO: Log a warning
}
// Even though the notion of ApplicationContext has been deprecated in favor of the notion of Environment we
// still keep this destruction for backward-compatibility.
// TODO: Add an Observation Even that we send when the Environment is destroyed so that we can move the code
// below in an Event Listener and move it to the legacy module.
try {
ApplicationContextListenerManager applicationContextListenerManager =
this.componentManager.getInstance(ApplicationContextListenerManager.class);
Container container = this.componentManager.getInstance(Container.class);
applicationContextListenerManager.destroyApplicationContext(container.getApplicationContext());
} catch (ComponentLookupException ex) {
// Nothing to do here.
// TODO: Log a warning
}
// Make sure to dispose all components before leaving
this.componentManager.dispose();
}
}
}
| xwiki-platform-core/xwiki-platform-containers/xwiki-platform-container-servlet/src/main/java/org/xwiki/container/servlet/XWikiServletContextListener.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.container.servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.xwiki.component.embed.EmbeddableComponentManager;
import org.xwiki.component.internal.StackingComponentEventManager;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.container.ApplicationContextListenerManager;
import org.xwiki.container.Container;
import org.xwiki.environment.Environment;
import org.xwiki.environment.internal.ServletEnvironment;
import org.xwiki.observation.ObservationManager;
import org.xwiki.observation.event.ApplicationStartedEvent;
import org.xwiki.observation.event.ApplicationStoppedEvent;
/**
* Implementation of the {@link ServletContextListener}. Initializes component manager and application context.
*
* @version $Id$
*/
public class XWikiServletContextListener implements ServletContextListener
{
/** The component manager used to lookup other components. */
private EmbeddableComponentManager componentManager;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent)
{
// Initializes the Embeddable Component Manager
EmbeddableComponentManager ecm = new EmbeddableComponentManager();
// Initialize all the components. Note that this can fail with a Runtime Exception. This is done voluntarily so
// that the XWiki webaopp will not be available if one component fails to load. It's better to fail-fast.
ecm.initialize(this.getClass().getClassLoader());
this.componentManager = ecm;
// This is a temporary bridge to allow non XWiki components to lookup XWiki components.
// We're putting the XWiki Component Manager instance in the Servlet Context so that it's
// available in the XWikiAction class which in turn puts it into the XWikiContext instance.
// Class that need to lookup then just need to get it from the XWikiContext instance.
// This is of course not necessary for XWiki components since they just need to implement
// the Composable interface to get access to the Component Manager or better they simply
// need to declare their components requirements using the @Inject annotation of the xwiki
// component manager together with a private class member, for automatic injection by the CM on init.
servletContextEvent.getServletContext().setAttribute(
org.xwiki.component.manager.ComponentManager.class.getName(), this.componentManager);
// Use a Component Event Manager that stacks Component instance creation events till we tell it to flush them.
// The reason is that the Observation Manager used to send the events but we need the Application Context to
// be set up before we start sending events since there can be Observation Listener components that require
// the Application Context (this is the case for example for the Office Importer Lifecycle Listener).
StackingComponentEventManager eventManager = new StackingComponentEventManager();
this.componentManager.setComponentEventManager(eventManager);
// Initialize the Environment
try {
ServletEnvironment servletEnvironment =
(ServletEnvironment) this.componentManager.getInstance(Environment.class);
servletEnvironment.setServletContext(servletContextEvent.getServletContext());
} catch (ComponentLookupException e) {
throw new RuntimeException("Failed to initialize the Servlet Environment", e);
}
// Initializes the Application Context.
// Even though the notion of ApplicationContext has been deprecated in favor of the notion of Environment we
// still keep this initialization for backward-compatibility.
// TODO: Add an Observation Even that we send when the Environment is initialized so that we can move the code
// below in an Event Listener and move it to the legacy module.
try {
ServletContainerInitializer containerInitializer =
this.componentManager.getInstance(ServletContainerInitializer.class);
containerInitializer.initializeApplicationContext(servletContextEvent.getServletContext());
} catch (ComponentLookupException e) {
throw new RuntimeException("Failed to initialize the Application Context", e);
}
// Send an Observation event to signal the XWiki application is started. This allows components who need to do
// something on startup to do it.
ObservationManager observationManager;
try {
observationManager = this.componentManager.getInstance(ObservationManager.class);
} catch (ComponentLookupException e) {
throw new RuntimeException("Failed to find the Observation Manager component", e);
}
// Now that the Application Context is set up, send the Component instance creation events we had stacked up.
eventManager.setObservationManager(observationManager);
eventManager.shouldStack(false);
eventManager.flushEvents();
// Indicate to the various components that XWiki is ready
observationManager.notify(new ApplicationStartedEvent(), this);
}
@Override
public void contextDestroyed(ServletContextEvent sce)
{
// It's possible that the Component Manager failed to initialize some of the required components.
if (this.componentManager != null) {
// Send an Observation event to signal the XWiki application is stopped. This allows components who need
// to do something on stop to do it.
try {
ObservationManager observationManager = this.componentManager.getInstance(ObservationManager.class);
observationManager.notify(new ApplicationStoppedEvent(), this);
} catch (ComponentLookupException e) {
// Nothing to do here.
// TODO: Log a warning
}
// Even though the notion of ApplicationContext has been deprecated in favor of the notion of Environment we
// still keep this destruction for backward-compatibility.
// TODO: Add an Observation Even that we send when the Environment is destroyed so that we can move the code
// below in an Event Listener and move it to the legacy module.
try {
ApplicationContextListenerManager applicationContextListenerManager =
this.componentManager.getInstance(ApplicationContextListenerManager.class);
Container container = this.componentManager.getInstance(Container.class);
applicationContextListenerManager.destroyApplicationContext(container.getApplicationContext());
} catch (ComponentLookupException ex) {
// Nothing to do here.
// TODO: Log a warning
}
// Make sure to dispose all components before leaving
this.componentManager.dispose();
}
}
}
| [Misc] Removed unnecessary cast
| xwiki-platform-core/xwiki-platform-containers/xwiki-platform-container-servlet/src/main/java/org/xwiki/container/servlet/XWikiServletContextListener.java | [Misc] Removed unnecessary cast | <ide><path>wiki-platform-core/xwiki-platform-containers/xwiki-platform-container-servlet/src/main/java/org/xwiki/container/servlet/XWikiServletContextListener.java
<ide>
<ide> // Initialize the Environment
<ide> try {
<del> ServletEnvironment servletEnvironment =
<del> (ServletEnvironment) this.componentManager.getInstance(Environment.class);
<add> ServletEnvironment servletEnvironment = this.componentManager.getInstance(Environment.class);
<ide> servletEnvironment.setServletContext(servletContextEvent.getServletContext());
<ide> } catch (ComponentLookupException e) {
<ide> throw new RuntimeException("Failed to initialize the Servlet Environment", e); |
|
Java | bsd-3-clause | b1f0dbe68aa71105a4997e9593f97ccafed0d3df | 0 | NCIP/cananolab,NCIP/cananolab,NCIP/cananolab | package gov.nih.nci.calab.service.common;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.Aliquot;
import gov.nih.nci.calab.domain.MeasureUnit;
import gov.nih.nci.calab.domain.Sample;
import gov.nih.nci.calab.domain.SampleContainer;
import gov.nih.nci.calab.domain.StorageElement;
import gov.nih.nci.calab.dto.inventory.AliquotBean;
import gov.nih.nci.calab.dto.inventory.ContainerBean;
import gov.nih.nci.calab.dto.inventory.ContainerInfoBean;
import gov.nih.nci.calab.dto.inventory.SampleBean;
import gov.nih.nci.calab.dto.workflow.AssayBean;
import gov.nih.nci.calab.service.util.CalabComparators;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import gov.nih.nci.calab.service.util.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.log4j.Logger;
import org.apache.struts.util.LabelValueBean;
/**
* The service to return prepopulated data that are shared across different
* views.
*
* @author zengje
*
*/
/* CVS $Id: LookupService.java,v 1.47 2006-09-05 21:29:45 pansu Exp $ */
public class LookupService {
private static Logger logger = Logger.getLogger(LookupService.class);
/**
* Retrieving all unmasked aliquots for use in views create run, use aliquot
* and create aliquot.
*
* @return a Map between sample name and its associated unmasked aliquots
* @throws Exception
*/
public Map<String, SortedSet<AliquotBean>> getUnmaskedSampleAliquots()
throws Exception {
SortedSet<AliquotBean> aliquots = null;
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Map<String, SortedSet<AliquotBean>> sampleAliquots = new HashMap<String, SortedSet<AliquotBean>>();
try {
ida.open();
String hqlString = "select aliquot.id, aliquot.name, aliquot.sample.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name";
List results = ida.search(hqlString);
for (Object obj : results) {
Object[] info = (Object[]) obj;
AliquotBean aliquot = new AliquotBean(StringUtils
.convertToString(info[0]), StringUtils
.convertToString(info[1]), CalabConstants.ACTIVE_STATUS);
String sampleName = (String) info[2];
if (sampleAliquots.get(sampleName) != null) {
aliquots = (SortedSet<AliquotBean>) sampleAliquots
.get(sampleName);
} else {
aliquots = new TreeSet<AliquotBean>(
new CalabComparators.AliquotBeanComparator());
sampleAliquots.put(sampleName, aliquots);
}
aliquots.add(aliquot);
}
} catch (Exception e) {
logger.error("Error in retrieving all aliquot Ids and names", e);
throw new RuntimeException(
"Error in retrieving all aliquot Ids and names");
} finally {
ida.close();
}
return sampleAliquots;
}
/**
*
* @return a map between sample name and its sample containers
* @throws Exception
*/
public Map<String, SortedSet<ContainerBean>> getAllSampleContainers()
throws Exception {
SortedSet<ContainerBean> containers = null;
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Map<String, SortedSet<ContainerBean>> sampleContainers = new HashMap<String, SortedSet<ContainerBean>>();
try {
ida.open();
String hqlString = "select container, container.sample.name from SampleContainer container";
List results = ida.search(hqlString);
for (Object obj : results) {
Object[] info = (Object[]) obj;
if (!(info[0] instanceof Aliquot)) {
ContainerBean container = new ContainerBean(
(SampleContainer) info[0]);
String sampleName = (String) info[1];
if (sampleContainers.get(sampleName) != null) {
containers = (SortedSet<ContainerBean>) sampleContainers
.get(sampleName);
} else {
containers = new TreeSet<ContainerBean>(
new CalabComparators.ContainerBeanComparator());
sampleContainers.put(sampleName, containers);
}
containers.add(container);
}
}
} catch (Exception e) {
logger.error("Error in retrieving all containers", e);
throw new RuntimeException("Error in retrieving all containers");
} finally {
ida.close();
}
return sampleContainers;
}
/**
* Retrieving all sample types.
*
* @return a list of all sample types
*/
public List<String> getAllSampleTypes() throws Exception {
// Detail here
// Retrieve data from Sample_Type table
List<String> sampleTypes = new ArrayList<String>();
sampleTypes.add(CalabConstants.OTHER);
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select sampleType.name from SampleType sampleType order by sampleType.name";
List results = ida.search(hqlString);
for (Object obj : results) {
sampleTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all sample types", e);
throw new RuntimeException("Error in retrieving all sample types");
} finally {
ida.close();
}
return sampleTypes;
}
/**
*
* @return the default sample container information in a form of
* ContainerInfoBean
*/
public ContainerInfoBean getSampleContainerInfo() throws Exception {
List<MeasureUnit> units = getAllMeasureUnits();
List<StorageElement> storageElements = getAllRoomAndFreezers();
List<String> quantityUnits = new ArrayList<String>();
List<String> concentrationUnits = new ArrayList<String>();
List<String> volumeUnits = new ArrayList<String>();
List<String> rooms = new ArrayList<String>();
List<String> freezers = new ArrayList<String>();
for (MeasureUnit unit : units) {
if (unit.getType().equalsIgnoreCase("Quantity")) {
quantityUnits.add(unit.getName());
} else if (unit.getType().equalsIgnoreCase("Volume")) {
volumeUnits.add(unit.getName());
} else if (unit.getType().equalsIgnoreCase("Concentration")) {
concentrationUnits.add(unit.getName());
}
}
for (StorageElement storageElement : storageElements) {
if (storageElement.getType().equalsIgnoreCase("Room")) {
rooms.add((storageElement.getLocation()));
} else if (storageElement.getType().equalsIgnoreCase("Freezer")) {
freezers.add((storageElement.getLocation()));
}
}
// set labs and racks to null for now
ContainerInfoBean containerInfo = new ContainerInfoBean(quantityUnits,
concentrationUnits, volumeUnits, null, rooms, freezers);
return containerInfo;
}
public List<String> getAllSampleContainerTypes() throws Exception {
SortedSet<String> containerTypes = new TreeSet<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType";
List results = ida.search(hqlString);
for (Object obj : results) {
containerTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all sample container types", e);
throw new RuntimeException(
"Error in retrieving all sample container types.");
} finally {
ida.close();
}
containerTypes.addAll(Arrays
.asList(CalabConstants.DEFAULT_CONTAINER_TYPES));
List<String> containerTypeList = new ArrayList<String>(containerTypes);
return containerTypeList;
}
public List<String> getAllAliquotContainerTypes() throws Exception {
SortedSet<String> containerTypes = new TreeSet<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select distinct aliquot.containerType from Aliquot aliquot order by aliquot.containerType";
List results = ida.search(hqlString);
for (Object obj : results) {
containerTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all aliquot container types", e);
throw new RuntimeException(
"Error in retrieving all aliquot container types.");
} finally {
ida.close();
}
containerTypes.addAll(Arrays
.asList(CalabConstants.DEFAULT_CONTAINER_TYPES));
List<String> containerTypeList = new ArrayList<String>(containerTypes);
return containerTypeList;
}
private List<MeasureUnit> getAllMeasureUnits() throws Exception {
List<MeasureUnit> units = new ArrayList<MeasureUnit>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "from MeasureUnit";
List results = ida.search(hqlString);
for (Object obj : results) {
units.add((MeasureUnit) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all measure units", e);
throw new RuntimeException("Error in retrieving all measure units.");
} finally {
ida.close();
}
return units;
}
private List<StorageElement> getAllRoomAndFreezers() throws Exception {
List<StorageElement> storageElements = new ArrayList<StorageElement>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "from StorageElement where type in ('Room', 'Freezer')";
List results = ida.search(hqlString);
for (Object obj : results) {
storageElements.add((StorageElement) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all rooms and freezers", e);
throw new RuntimeException(
"Error in retrieving all rooms and freezers.");
} finally {
ida.close();
}
return storageElements;
}
/**
*
* @return the default sample container information in a form of
* ContainerInfoBean
*/
public ContainerInfoBean getAliquotContainerInfo() throws Exception {
return getSampleContainerInfo();
}
/**
* Get all samples in the database
*
* @return a list of SampleBean containing sample Ids and names DELETE
*/
public List<SampleBean> getAllSamples() throws Exception {
List<SampleBean> samples = new ArrayList<SampleBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select sample.id, sample.name from Sample sample";
List results = ida.search(hqlString);
for (Object obj : results) {
Object[] sampleInfo = (Object[]) obj;
samples.add(new SampleBean(StringUtils
.convertToString(sampleInfo[0]), StringUtils
.convertToString(sampleInfo[1])));
}
} catch (Exception e) {
logger.error("Error in retrieving all sample IDs and names", e);
throw new RuntimeException(
"Error in retrieving all sample IDs and names");
} finally {
ida.close();
}
Collections.sort(samples, new CalabComparators.SampleBeanComparator());
return samples;
}
/**
* Retrieve all Assay Types from the system
*
* @return A list of all assay type
*/
public List getAllAssayTypes() throws Exception {
List<String> assayTypes = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder";
List results = ida.search(hqlString);
for (Object obj : results) {
assayTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all assay types", e);
throw new RuntimeException("Error in retrieving all assay types");
} finally {
ida.close();
}
return assayTypes;
}
/**
*
* @return a map between assay type and its assays
* @throws Exception
*/
public Map<String, SortedSet<AssayBean>> getAllAssayTypeAssays()
throws Exception {
Map<String, SortedSet<AssayBean>> assayTypeAssays = new HashMap<String, SortedSet<AssayBean>>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay";
List results = ida.search(hqlString);
SortedSet<AssayBean> assays = null;
for (Object obj : results) {
Object[] objArray = (Object[]) obj;
AssayBean assay = new AssayBean(
((Long) objArray[0]).toString(), (String) objArray[1],
(String) objArray[2]);
if (assayTypeAssays.get(assay.getAssayType()) != null) {
assays = (SortedSet<AssayBean>) assayTypeAssays.get(assay
.getAssayType());
} else {
assays = new TreeSet<AssayBean>(
new CalabComparators.AssayBeanComparator());
assayTypeAssays.put(assay.getAssayType(), assays);
}
assays.add(assay);
}
} catch (Exception e) {
logger.error("Error in retrieving all assay beans. ", e);
throw new RuntimeException("Error in retrieving all assays beans. ");
} finally {
ida.close();
}
return assayTypeAssays;
}
/**
*
* @return all sample sources
*/
public List<String> getAllSampleSources() throws Exception {
List<String> sampleSources = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select source.organizationName from Source source order by source.organizationName";
List results = ida.search(hqlString);
for (Object obj : results) {
sampleSources.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all sample sources", e);
throw new RuntimeException("Error in retrieving all sample sources");
} finally {
ida.close();
}
return sampleSources;
}
/**
*
* @return a map between sample source and samples with unmasked aliquots
* @throws Exception
*/
public Map<String, SortedSet<SampleBean>> getSampleSourceSamplesWithUnmaskedAliquots()
throws Exception {
Map<String, SortedSet<SampleBean>> sampleSourceSamples = new HashMap<String, SortedSet<SampleBean>>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select distinct aliquot.sample from Aliquot aliquot where aliquot.dataStatus is null";
List results = ida.search(hqlString);
SortedSet<SampleBean> samples = null;
for (Object obj : results) {
SampleBean sample = new SampleBean((Sample) obj);
if (sampleSourceSamples.get(sample.getSampleSource()) != null) {
// TODO need to make sample source a required field
if (sample.getSampleSource().length() > 0) {
samples = (SortedSet<SampleBean>) sampleSourceSamples
.get(sample.getSampleSource());
}
} else {
samples = new TreeSet<SampleBean>(
new CalabComparators.SampleBeanComparator());
if (sample.getSampleSource().length() > 0) {
sampleSourceSamples.put(sample.getSampleSource(),
samples);
}
}
samples.add(sample);
}
} catch (Exception e) {
logger.error(
"Error in retrieving sample beans with unmasked aliquots ",
e);
throw new RuntimeException(
"Error in retrieving all sample beans with unmasked aliquots. ");
} finally {
ida.close();
}
return sampleSourceSamples;
}
public List<String> getAllSampleSOPs() throws Exception {
List<String> sampleSOPs = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select sampleSOP.name from SampleSOP sampleSOP where sampleSOP.description='sample creation'";
List results = ida.search(hqlString);
for (Object obj : results) {
sampleSOPs.add((String) obj);
}
} catch (Exception e) {
logger.error("Problem to retrieve all Sample SOPs.");
throw new RuntimeException("Problem to retrieve all Sample SOPs. ");
} finally {
ida.close();
}
return sampleSOPs;
}
/**
*
* @return all methods for creating aliquots
*/
public List<LabelValueBean> getAliquotCreateMethods() throws Exception {
List<LabelValueBean> createMethods = new ArrayList<LabelValueBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select sop.name, file.path from SampleSOP sop join sop.sampleSOPFileCollection file where sop.description='aliquot creation'";
List results = ida.search(hqlString);
for (Object obj : results) {
String sopName = (String) ((Object[]) obj)[0];
String sopURI = (String) ((Object[]) obj)[1];
String sopURL = (sopURI == null) ? "" : sopURI;
createMethods.add(new LabelValueBean(sopName, sopURL));
}
} catch (Exception e) {
logger.error("Error in retrieving all sample sources", e);
throw new RuntimeException("Error in retrieving all sample sources");
} finally {
ida.close();
}
return createMethods;
}
/**
*
* @return all source sample IDs
*/
public List<String> getAllSourceSampleIds() throws Exception {
List<String> sourceSampleIds = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select distinct sample.sourceSampleId from Sample sample order by sample.sourceSampleId";
List results = ida.search(hqlString);
for (Object obj : results) {
sourceSampleIds.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all source sample IDs", e);
throw new RuntimeException(
"Error in retrieving all source sample IDs");
} finally {
ida.close();
}
return sourceSampleIds;
}
public Map<String, SortedSet<String>> getAllParticleTypeParticles()
throws Exception {
// TODO fill in actual database query.
Map<String, SortedSet<String>> particleTypeParticles = new HashMap<String, SortedSet<String>>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select particle.type, particle.name from Nanoparticle particle";
List results = ida.search(hqlString);
SortedSet<String> particleNames = null;
for (Object obj : results) {
Object[] objArray = (Object[]) obj;
String particleType = (String) objArray[0];
String particleName = (String) objArray[1];
if (particleType != null) {
if (particleTypeParticles.get(particleType) != null) {
particleNames = (SortedSet<String>) particleTypeParticles
.get(particleType);
} else {
particleNames = new TreeSet<String>(
new CalabComparators.SortableNameComparator());
particleTypeParticles.put(particleType, particleNames);
}
particleNames.add(particleName);
}
}
} catch (Exception e) {
logger
.error("Error in retrieving all particle type particles. ",
e);
throw new RuntimeException(
"Error in retrieving all particle type particles. ");
} finally {
ida.close();
}
return particleTypeParticles;
}
public String[] getAllParticleFunctions() {
String[] functions = new String[] { "Therapeutic", "Targeting",
"Diagnostic Imaging", "Diagnostic Reporting" };
return functions;
}
public String[] getAllCharacterizationTypes() {
String[] charTypes = new String[] { "Physical Characterization",
"In Vitro Characterization", "In Vivo Characterization" };
return charTypes;
}
public String[] getAllDendrimerCores() {
String[] cores = new String[] { "Diamine", "Ethyline" };
return cores;
}
public String[] getAllDendrimerSurfaceGroupNames() {
String[] names = new String[] { "Amine", "Carboxyl", "Hydroxyl" };
return names;
}
public String[] getAllMetalCompositions() {
String[] compositions = new String[] { "Gold", "Sliver", "Iron oxide" };
return compositions;
}
public String[] getAllPolymerInitiators() {
String[] initiators = new String[] { "Free Radicals", "Peroxide" };
return initiators;
}
public List<String> getAllParticleSources() throws Exception {
// TODO fill in db code
return getAllSampleSources();
}
public String getParticleClassification(String particleType) {
String key = "classification." + particleType.replaceAll(" ", "_");
String classification = PropertyReader.getProperty(
CalabConstants.PARTICLE_PROPERTY, key);
return classification;
}
/**
*
* @return a map between a characterization type and its child
* characterizations.
*/
public Map<String, String[]> getCharacterizationTypeCharacterizations() {
Map<String, String[]> charTypeChars = new HashMap<String, String[]>();
String[] physicalChars = new String[] { "Composition", "Size",
"Molecular Weight", "Morphology", "Surface Characteristics",
"Solubility", "Purity", "Stability" };
charTypeChars.put("physical", physicalChars);
String[] toxChars = new String[] { "Oxidative Stress",
"Enzyme Function" };
charTypeChars.put("toxicity", toxChars);
String[] cytoToxChars = new String[] { "MTT", "LDH",
"Caspase 3 Activation" };
charTypeChars.put("cytoTox", cytoToxChars);
String[] bloodContactChars = new String[] { "Plate Aggregation",
"Hemolysis", "Plasma Protein Binding", "Coagulation" };
charTypeChars.put("bloodContactTox", bloodContactChars);
String[] immuneCellFuncChars = new String[] { "Oxidative Burst",
"Chemotaxis", "Leukocyte Proliferation", "Phagocytosis",
"Cytokine Induction", "CFU-GM", "Complement Activation",
"Cytotoxic Activity of NK Cells" };
charTypeChars.put("immuneCellFuncTox", immuneCellFuncChars);
String[] metabolicChars = new String[] { "CYP450",
"Glucuronidation, Sulphation", "ROS" };
charTypeChars.put("metabolicStabilityTox", metabolicChars);
return charTypeChars;
}
}
| src/gov/nih/nci/calab/service/common/LookupService.java | package gov.nih.nci.calab.service.common;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.Aliquot;
import gov.nih.nci.calab.domain.MeasureUnit;
import gov.nih.nci.calab.domain.Sample;
import gov.nih.nci.calab.domain.SampleContainer;
import gov.nih.nci.calab.domain.StorageElement;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.inventory.AliquotBean;
import gov.nih.nci.calab.dto.inventory.ContainerBean;
import gov.nih.nci.calab.dto.inventory.ContainerInfoBean;
import gov.nih.nci.calab.dto.inventory.SampleBean;
import gov.nih.nci.calab.dto.workflow.AssayBean;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.util.CalabComparators;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import gov.nih.nci.calab.service.util.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.log4j.Logger;
import org.apache.struts.util.LabelValueBean;
/**
* The service to return prepopulated data that are shared across different
* views.
*
* @author zengje
*
*/
/* CVS $Id: LookupService.java,v 1.46 2006-09-05 05:22:20 zengje Exp $ */
public class LookupService {
private static Logger logger = Logger.getLogger(LookupService.class);
/**
* Retrieving all unmasked aliquots for use in views create run, use aliquot
* and create aliquot.
*
* @return a Map between sample name and its associated unmasked aliquots
* @throws Exception
*/
public Map<String, SortedSet<AliquotBean>> getUnmaskedSampleAliquots()
throws Exception {
SortedSet<AliquotBean> aliquots = null;
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Map<String, SortedSet<AliquotBean>> sampleAliquots = new HashMap<String, SortedSet<AliquotBean>>();
try {
ida.open();
String hqlString = "select aliquot.id, aliquot.name, aliquot.sample.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name";
List results = ida.search(hqlString);
for (Object obj : results) {
Object[] info = (Object[]) obj;
AliquotBean aliquot = new AliquotBean(StringUtils
.convertToString(info[0]), StringUtils
.convertToString(info[1]), CalabConstants.ACTIVE_STATUS);
String sampleName = (String) info[2];
if (sampleAliquots.get(sampleName) != null) {
aliquots = (SortedSet<AliquotBean>) sampleAliquots
.get(sampleName);
} else {
aliquots = new TreeSet<AliquotBean>(
new CalabComparators.AliquotBeanComparator());
sampleAliquots.put(sampleName, aliquots);
}
aliquots.add(aliquot);
}
} catch (Exception e) {
logger.error("Error in retrieving all aliquot Ids and names", e);
throw new RuntimeException(
"Error in retrieving all aliquot Ids and names");
} finally {
ida.close();
}
return sampleAliquots;
}
/**
*
* @return a map between sample name and its sample containers
* @throws Exception
*/
public Map<String, SortedSet<ContainerBean>> getAllSampleContainers()
throws Exception {
SortedSet<ContainerBean> containers = null;
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Map<String, SortedSet<ContainerBean>> sampleContainers = new HashMap<String, SortedSet<ContainerBean>>();
try {
ida.open();
String hqlString = "select container, container.sample.name from SampleContainer container";
List results = ida.search(hqlString);
for (Object obj : results) {
Object[] info = (Object[]) obj;
if (!(info[0] instanceof Aliquot)) {
ContainerBean container = new ContainerBean(
(SampleContainer) info[0]);
String sampleName = (String) info[1];
if (sampleContainers.get(sampleName) != null) {
containers = (SortedSet<ContainerBean>) sampleContainers
.get(sampleName);
} else {
containers = new TreeSet<ContainerBean>(
new CalabComparators.ContainerBeanComparator());
sampleContainers.put(sampleName, containers);
}
containers.add(container);
}
}
} catch (Exception e) {
logger.error("Error in retrieving all containers", e);
throw new RuntimeException("Error in retrieving all containers");
} finally {
ida.close();
}
return sampleContainers;
}
/**
* Retrieving all sample types.
*
* @return a list of all sample types
*/
public List<String> getAllSampleTypes() throws Exception {
// Detail here
// Retrieve data from Sample_Type table
List<String> sampleTypes = new ArrayList<String>();
sampleTypes.add(CalabConstants.OTHER);
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select sampleType.name from SampleType sampleType order by sampleType.name";
List results = ida.search(hqlString);
for (Object obj : results) {
sampleTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all sample types", e);
throw new RuntimeException("Error in retrieving all sample types");
} finally {
ida.close();
}
return sampleTypes;
}
/**
*
* @return the default sample container information in a form of
* ContainerInfoBean
*/
public ContainerInfoBean getSampleContainerInfo() throws Exception {
List<MeasureUnit> units = getAllMeasureUnits();
List<StorageElement> storageElements = getAllRoomAndFreezers();
List<String> quantityUnits = new ArrayList<String>();
List<String> concentrationUnits = new ArrayList<String>();
List<String> volumeUnits = new ArrayList<String>();
List<String> rooms = new ArrayList<String>();
List<String> freezers = new ArrayList<String>();
for (MeasureUnit unit : units) {
if (unit.getType().equalsIgnoreCase("Quantity")) {
quantityUnits.add(unit.getName());
} else if (unit.getType().equalsIgnoreCase("Volume")) {
volumeUnits.add(unit.getName());
} else if (unit.getType().equalsIgnoreCase("Concentration")) {
concentrationUnits.add(unit.getName());
}
}
for (StorageElement storageElement : storageElements) {
if (storageElement.getType().equalsIgnoreCase("Room")) {
rooms.add((storageElement.getLocation()));
} else if (storageElement.getType().equalsIgnoreCase("Freezer")) {
freezers.add((storageElement.getLocation()));
}
}
// set labs and racks to null for now
ContainerInfoBean containerInfo = new ContainerInfoBean(quantityUnits,
concentrationUnits, volumeUnits, null, rooms, freezers);
return containerInfo;
}
public List<String> getAllSampleContainerTypes() throws Exception {
SortedSet<String> containerTypes = new TreeSet<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType";
List results = ida.search(hqlString);
for (Object obj : results) {
containerTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all sample container types", e);
throw new RuntimeException(
"Error in retrieving all sample container types.");
} finally {
ida.close();
}
containerTypes.addAll(Arrays
.asList(CalabConstants.DEFAULT_CONTAINER_TYPES));
List<String> containerTypeList = new ArrayList<String>(containerTypes);
return containerTypeList;
}
public List<String> getAllAliquotContainerTypes() throws Exception {
SortedSet<String> containerTypes = new TreeSet<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select distinct aliquot.containerType from Aliquot aliquot order by aliquot.containerType";
List results = ida.search(hqlString);
for (Object obj : results) {
containerTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all aliquot container types", e);
throw new RuntimeException(
"Error in retrieving all aliquot container types.");
} finally {
ida.close();
}
containerTypes.addAll(Arrays
.asList(CalabConstants.DEFAULT_CONTAINER_TYPES));
List<String> containerTypeList = new ArrayList<String>(containerTypes);
return containerTypeList;
}
private List<MeasureUnit> getAllMeasureUnits() throws Exception {
List<MeasureUnit> units = new ArrayList<MeasureUnit>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "from MeasureUnit";
List results = ida.search(hqlString);
for (Object obj : results) {
units.add((MeasureUnit) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all measure units", e);
throw new RuntimeException("Error in retrieving all measure units.");
} finally {
ida.close();
}
return units;
}
private List<StorageElement> getAllRoomAndFreezers() throws Exception {
List<StorageElement> storageElements = new ArrayList<StorageElement>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "from StorageElement where type in ('Room', 'Freezer')";
List results = ida.search(hqlString);
for (Object obj : results) {
storageElements.add((StorageElement) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all rooms and freezers", e);
throw new RuntimeException(
"Error in retrieving all rooms and freezers.");
} finally {
ida.close();
}
return storageElements;
}
/**
*
* @return the default sample container information in a form of
* ContainerInfoBean
*/
public ContainerInfoBean getAliquotContainerInfo() throws Exception {
return getSampleContainerInfo();
}
/**
* Get all samples in the database
*
* @return a list of SampleBean containing sample Ids and names DELETE
*/
public List<SampleBean> getAllSamples() throws Exception {
List<SampleBean> samples = new ArrayList<SampleBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select sample.id, sample.name from Sample sample";
List results = ida.search(hqlString);
for (Object obj : results) {
Object[] sampleInfo = (Object[]) obj;
samples.add(new SampleBean(StringUtils
.convertToString(sampleInfo[0]), StringUtils
.convertToString(sampleInfo[1])));
}
} catch (Exception e) {
logger.error("Error in retrieving all sample IDs and names", e);
throw new RuntimeException(
"Error in retrieving all sample IDs and names");
} finally {
ida.close();
}
Collections.sort(samples, new CalabComparators.SampleBeanComparator());
return samples;
}
/**
* Retrieve all Assay Types from the system
*
* @return A list of all assay type
*/
public List getAllAssayTypes() throws Exception {
List<String> assayTypes = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder";
List results = ida.search(hqlString);
for (Object obj : results) {
assayTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all assay types", e);
throw new RuntimeException("Error in retrieving all assay types");
} finally {
ida.close();
}
return assayTypes;
}
/**
*
* @return a map between assay type and its assays
* @throws Exception
*/
public Map<String, SortedSet<AssayBean>> getAllAssayTypeAssays()
throws Exception {
Map<String, SortedSet<AssayBean>> assayTypeAssays = new HashMap<String, SortedSet<AssayBean>>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay";
List results = ida.search(hqlString);
SortedSet<AssayBean> assays = null;
for (Object obj : results) {
Object[] objArray = (Object[]) obj;
AssayBean assay = new AssayBean(
((Long) objArray[0]).toString(), (String) objArray[1],
(String) objArray[2]);
if (assayTypeAssays.get(assay.getAssayType()) != null) {
assays = (SortedSet<AssayBean>) assayTypeAssays.get(assay
.getAssayType());
} else {
assays = new TreeSet<AssayBean>(
new CalabComparators.AssayBeanComparator());
assayTypeAssays.put(assay.getAssayType(), assays);
}
assays.add(assay);
}
} catch (Exception e) {
logger.error("Error in retrieving all assay beans. ", e);
throw new RuntimeException("Error in retrieving all assays beans. ");
} finally {
ida.close();
}
return assayTypeAssays;
}
/**
*
* @return all sample sources
*/
public List<String> getAllSampleSources() throws Exception {
List<String> sampleSources = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select source.organizationName from Source source order by source.organizationName";
List results = ida.search(hqlString);
for (Object obj : results) {
sampleSources.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all sample sources", e);
throw new RuntimeException("Error in retrieving all sample sources");
} finally {
ida.close();
}
return sampleSources;
}
/**
*
* @return a map between sample source and samples with unmasked aliquots
* @throws Exception
*/
public Map<String, SortedSet<SampleBean>> getSampleSourceSamplesWithUnmaskedAliquots()
throws Exception {
Map<String, SortedSet<SampleBean>> sampleSourceSamples = new HashMap<String, SortedSet<SampleBean>>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select distinct aliquot.sample from Aliquot aliquot where aliquot.dataStatus is null";
List results = ida.search(hqlString);
SortedSet<SampleBean> samples = null;
for (Object obj : results) {
SampleBean sample = new SampleBean((Sample) obj);
if (sampleSourceSamples.get(sample.getSampleSource()) != null) {
// TODO need to make sample source a required field
if (sample.getSampleSource().length() > 0) {
samples = (SortedSet<SampleBean>) sampleSourceSamples
.get(sample.getSampleSource());
}
} else {
samples = new TreeSet<SampleBean>(
new CalabComparators.SampleBeanComparator());
if (sample.getSampleSource().length() > 0) {
sampleSourceSamples.put(sample.getSampleSource(),
samples);
}
}
samples.add(sample);
}
} catch (Exception e) {
logger.error(
"Error in retrieving sample beans with unmasked aliquots ",
e);
throw new RuntimeException(
"Error in retrieving all sample beans with unmasked aliquots. ");
} finally {
ida.close();
}
return sampleSourceSamples;
}
public List<String> getAllSampleSOPs() throws Exception {
List<String> sampleSOPs = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select sampleSOP.name from SampleSOP sampleSOP where sampleSOP.description='sample creation'";
List results = ida.search(hqlString);
for (Object obj : results) {
sampleSOPs.add((String) obj);
}
} catch (Exception e) {
logger.error("Problem to retrieve all Sample SOPs.");
throw new RuntimeException("Problem to retrieve all Sample SOPs. ");
} finally {
ida.close();
}
return sampleSOPs;
}
/**
*
* @return all methods for creating aliquots
*/
public List<LabelValueBean> getAliquotCreateMethods() throws Exception {
List<LabelValueBean> createMethods = new ArrayList<LabelValueBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select sop.name, file.path from SampleSOP sop join sop.sampleSOPFileCollection file where sop.description='aliquot creation'";
List results = ida.search(hqlString);
for (Object obj : results) {
String sopName = (String) ((Object[]) obj)[0];
String sopURI = (String) ((Object[]) obj)[1];
String sopURL = (sopURI == null) ? "" : sopURI;
createMethods.add(new LabelValueBean(sopName, sopURL));
}
} catch (Exception e) {
logger.error("Error in retrieving all sample sources", e);
throw new RuntimeException("Error in retrieving all sample sources");
} finally {
ida.close();
}
return createMethods;
}
/**
*
* @return all source sample IDs
*/
public List<String> getAllSourceSampleIds() throws Exception {
List<String> sourceSampleIds = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select distinct sample.sourceSampleId from Sample sample order by sample.sourceSampleId";
List results = ida.search(hqlString);
for (Object obj : results) {
sourceSampleIds.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all source sample IDs", e);
throw new RuntimeException(
"Error in retrieving all source sample IDs");
} finally {
ida.close();
}
return sourceSampleIds;
}
public Map<String, SortedSet<String>> getAllParticleTypeParticles()
throws Exception {
// TODO fill in actual database query.
Map<String, SortedSet<String>> particleTypeParticles = new HashMap<String, SortedSet<String>>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select particle.type, particle.name from Nanoparticle particle";
List results = ida.search(hqlString);
SortedSet<String> particleNames = null;
for (Object obj : results) {
Object[] objArray = (Object[]) obj;
String particleType = (String) objArray[0];
String particleName = (String) objArray[1];
if (particleType != null) {
if (particleTypeParticles.get(particleType) != null) {
particleNames = (SortedSet<String>) particleTypeParticles
.get(particleType);
} else {
particleNames = new TreeSet<String>(
new CalabComparators.SortableNameComparator());
particleTypeParticles.put(particleType, particleNames);
}
particleNames.add(particleName);
}
}
} catch (Exception e) {
logger
.error("Error in retrieving all particle type particles. ",
e);
throw new RuntimeException(
"Error in retrieving all particle type particles. ");
} finally {
ida.close();
}
return particleTypeParticles;
}
public String[] getAllParticleFunctions() {
String[] functions = new String[] { "Therapeutic", "Targeting",
"Diagnostic Imaging", "Diagnostic Reporting" };
return functions;
}
public String[] getAllCharacterizationTypes() {
String[] charTypes = new String[] { "Physical Characterization",
"In Vitro Characterization", "In Vivo Characterization" };
return charTypes;
}
public String[] getAllDendrimerCores() {
String[] cores = new String[] { "Diamine", "Ethyline" };
return cores;
}
public String[] getAllDendrimerSurfaceGroupNames() {
String[] names = new String[] { "Amine", "Carboxyl", "Hydroxyl" };
return names;
}
public String[] getAllMetalCompositions() {
String[] compositions = new String[] { "Gold", "Sliver", "Iron oxide" };
return compositions;
}
public String[] getAllPolymerInitiators() {
String[] initiators = new String[] { "Free Radicals", "Peroxide" };
return initiators;
}
public List<String> getAllParticleSources() throws Exception {
// TODO fill in db code
return getAllSampleSources();
}
// public Map<String, String> getParticleTypeToParticleCategory() {
// Map<String, String> type2Category = new HashMap<String, String>();
// // TODO replaced by database code
// type2Category.put("polymer", "organic-hydrocarbon");
// type2Category.put("dendrimer", "organic-hydrocarbon");
// type2Category.put("carbon nanotube", "organic-carbon");
// type2Category.put("fullerene", "organic-carbon");
// type2Category.put("quantom dot", "inorganic");
// type2Category.put("metal particle", "inorganic");
// type2Category.put("liposome", "organic");
// type2Category.put("emulsion", "organic");
// type2Category.put("complex particle", "complex");
// return type2Category;
// }
public String getParticleClassification(String particleType) {
String key= "classification."+particleType.replaceAll(" ", "_");
String classification = PropertyReader.getProperty(CalabConstants.PARTICLE_PROPERTY,key);
return classification;
}
/**
*
* @return a map between a characterization type and its child characterizations.
*/
public Map<String, String[]> getCharacterizationTypeCharacterizations() {
Map<String, String[]> charTypeChars = new HashMap<String, String[]>();
String[] physicalChars = new String[] { "Composition", "Size",
"Molecular Weight", "Morphology", "Surface Characteristics",
"Solubility", "Purity", "Stability" };
charTypeChars.put("physical", physicalChars);
String[] toxChars = new String[] { "Oxidative Stress",
"Enzyme Function" };
charTypeChars.put("toxicity", toxChars);
String[] cytoToxChars = new String[] { "MTT", "LDH",
"Caspase 3 Activation" };
charTypeChars.put("cytoTox", cytoToxChars);
String[] bloodContactChars = new String[] { "Plate Aggregation",
"Hemolysis", "Plasma Protein Binding", "Coagulation" };
charTypeChars.put("bloodContactTox", bloodContactChars);
String[] immuneCellFuncChars = new String[] { "Oxidative Burst",
"Chemotaxis", "Leukocyte Proliferation", "Phagocytosis",
"Cytokine Induction", "CFU-GM", "Complement Activation",
"Cytotoxic Activity of NK Cells" };
charTypeChars.put("immuneCellFuncTox", immuneCellFuncChars);
String[] metabolicChars = new String[] { "CYP450",
"Glucuronidation, Sulphation", "ROS" };
charTypeChars.put("metabolicStabilityTox", metabolicChars);
return charTypeChars;
}
}
| optimized imports
SVN-Revision: 1765
| src/gov/nih/nci/calab/service/common/LookupService.java | optimized imports | <ide><path>rc/gov/nih/nci/calab/service/common/LookupService.java
<ide> import gov.nih.nci.calab.domain.Sample;
<ide> import gov.nih.nci.calab.domain.SampleContainer;
<ide> import gov.nih.nci.calab.domain.StorageElement;
<del>import gov.nih.nci.calab.dto.common.UserBean;
<ide> import gov.nih.nci.calab.dto.inventory.AliquotBean;
<ide> import gov.nih.nci.calab.dto.inventory.ContainerBean;
<ide> import gov.nih.nci.calab.dto.inventory.ContainerInfoBean;
<ide> import gov.nih.nci.calab.dto.inventory.SampleBean;
<ide> import gov.nih.nci.calab.dto.workflow.AssayBean;
<del>import gov.nih.nci.calab.service.security.UserService;
<ide> import gov.nih.nci.calab.service.util.CalabComparators;
<ide> import gov.nih.nci.calab.service.util.CalabConstants;
<ide> import gov.nih.nci.calab.service.util.PropertyReader;
<ide> * @author zengje
<ide> *
<ide> */
<del>/* CVS $Id: LookupService.java,v 1.46 2006-09-05 05:22:20 zengje Exp $ */
<add>/* CVS $Id: LookupService.java,v 1.47 2006-09-05 21:29:45 pansu Exp $ */
<ide>
<ide> public class LookupService {
<ide> private static Logger logger = Logger.getLogger(LookupService.class);
<ide> return getAllSampleSources();
<ide> }
<ide>
<del>// public Map<String, String> getParticleTypeToParticleCategory() {
<del>// Map<String, String> type2Category = new HashMap<String, String>();
<del>// // TODO replaced by database code
<del>// type2Category.put("polymer", "organic-hydrocarbon");
<del>// type2Category.put("dendrimer", "organic-hydrocarbon");
<del>// type2Category.put("carbon nanotube", "organic-carbon");
<del>// type2Category.put("fullerene", "organic-carbon");
<del>// type2Category.put("quantom dot", "inorganic");
<del>// type2Category.put("metal particle", "inorganic");
<del>// type2Category.put("liposome", "organic");
<del>// type2Category.put("emulsion", "organic");
<del>// type2Category.put("complex particle", "complex");
<del>// return type2Category;
<del>// }
<del>
<ide> public String getParticleClassification(String particleType) {
<del> String key= "classification."+particleType.replaceAll(" ", "_");
<del> String classification = PropertyReader.getProperty(CalabConstants.PARTICLE_PROPERTY,key);
<add> String key = "classification." + particleType.replaceAll(" ", "_");
<add> String classification = PropertyReader.getProperty(
<add> CalabConstants.PARTICLE_PROPERTY, key);
<ide> return classification;
<ide>
<ide> }
<del> /**
<del> *
<del> * @return a map between a characterization type and its child characterizations.
<add>
<add> /**
<add> *
<add> * @return a map between a characterization type and its child
<add> * characterizations.
<ide> */
<ide> public Map<String, String[]> getCharacterizationTypeCharacterizations() {
<ide> Map<String, String[]> charTypeChars = new HashMap<String, String[]>(); |
|
Java | apache-2.0 | 7ff6bbfe430d449eb8f4f06b6cef8ca279442f2c | 0 | cisco-open-source/selenium,cisco-open-source/selenium,cisco-open-source/selenium,cisco-open-source/selenium,cisco-open-source/selenium,cisco-open-source/selenium,cisco-open-source/selenium,cisco-open-source/selenium,cisco-open-source/selenium | /*
Copyright 2012 Software Freedom Conservancy
Copyright 2007-2012 WebDriver committers
Copyright 2007-2009 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.environment.webserver;
import org.openqa.selenium.net.NetworkUtils;
import org.openqa.selenium.testing.InProject;
import org.seleniumhq.jetty7.server.Connector;
import org.seleniumhq.jetty7.server.Handler;
import org.seleniumhq.jetty7.server.Server;
import org.seleniumhq.jetty7.server.handler.ContextHandlerCollection;
import org.seleniumhq.jetty7.server.nio.SelectChannelConnector;
import org.seleniumhq.jetty7.server.ssl.SslSocketConnector;
import org.seleniumhq.jetty7.servlet.ServletHolder;
import org.seleniumhq.jetty7.servlets.MultiPartFilter;
import org.seleniumhq.jetty7.webapp.WebAppContext;
import java.io.File;
import javax.servlet.Filter;
import javax.servlet.Servlet;
import static org.openqa.selenium.net.PortProber.findFreePort;
import static org.openqa.selenium.testing.InProject.locate;
public class Jetty7AppServer implements AppServer {
private static final String HOSTNAME_FOR_TEST_ENV_NAME = "HOSTNAME";
private static final String ALTERNATIVE_HOSTNAME_FOR_TEST_ENV_NAME = "ALTERNATIVE_HOSTNAME";
private static final String FIXED_HTTP_PORT_ENV_NAME = "TEST_HTTP_PORT";
private static final String FIXED_HTTPS_PORT_ENV_NAME = "TEST_HTTPS_PORT";
private static final int DEFAULT_HTTP_PORT = 2310;
private static final int DEFAULT_HTTPS_PORT = 2410;
private static final String DEFAULT_CONTEXT_PATH = "/common";
private static final String JS_SRC_CONTEXT_PATH = "/javascript";
private static final String CLOSURE_CONTEXT_PATH = "/third_party/closure/goog";
private static final String THIRD_PARTY_JS_CONTEXT_PATH = "/third_party/js";
private static final NetworkUtils networkUtils = new NetworkUtils();
private int port;
private int securePort;
private File path;
private File jsSrcRoot;
private final Server server;
private WebAppContext defaultContext;
private WebAppContext jsContext;
private ContextHandlerCollection handlers;
private final String hostName;
public Jetty7AppServer() {
this(detectHostname());
}
public static String detectHostname() {
String hostnameFromProperty = System.getenv(HOSTNAME_FOR_TEST_ENV_NAME);
return hostnameFromProperty == null ? "localhost" : hostnameFromProperty;
}
public Jetty7AppServer(String hostName) {
this.hostName = hostName;
// Be quiet. Unless we want things to be chatty
if (!Boolean.getBoolean("webdriver.debug")) {
new NullLogger().disableLogging();
}
server = new Server();
path = findRootOfWebApp();
jsSrcRoot = findJsSrcWebAppRoot();
handlers = new ContextHandlerCollection();
defaultContext = addWebApplication(DEFAULT_CONTEXT_PATH, path);
jsContext = addWebApplication(JS_SRC_CONTEXT_PATH, jsSrcRoot);
addWebApplication(CLOSURE_CONTEXT_PATH, locate("third_party/closure/goog"));
addWebApplication(THIRD_PARTY_JS_CONTEXT_PATH, locate("third_party/js"));
server.setHandler(handlers);
addServlet("Redirecter", "/redirect", RedirectServlet.class);
addServlet("InfinitePagerServer", "/page/*", PageServlet.class);
addServlet(defaultContext, "Manifest", "/manifest/*", ManifestServlet.class);
addServlet(defaultContext, "Manifest", "*.appcache", ManifestServlet.class);
addServlet(jsContext, "Manifest", "*.appcache", ManifestServlet.class);
// Serves every file under DEFAULT_CONTEXT_PATH/utf8 as UTF-8 to the browser
addServlet(defaultContext, "UTF8", "/utf8/*", Utf8Servlet.class);
addServlet("Uploader", "/upload", UploadServlet.class);
addServlet("Unusual encoding", "/encoding", EncodingServlet.class);
addServlet("Sleeper", "/sleep", SleepingServlet.class);
addServlet("Kill switch", "/quitquitquit", KillSwitchServlet.class);
addServlet("Basic Authentication", "/basicAuth", BasicAuth.class);
addFilter(MultiPartFilter.class, "/upload", 0 /* DEFAULT dispatches */);
listenOn(getHttpPort());
listenSecurelyOn(getHttpsPort());
}
private int getHttpPort() {
String port = System.getenv(FIXED_HTTP_PORT_ENV_NAME);
return port == null ? findFreePort() : Integer.parseInt(port);
}
private int getHttpsPort() {
String port = System.getenv(FIXED_HTTPS_PORT_ENV_NAME);
return port == null ? findFreePort() : Integer.parseInt(port);
}
protected File findRootOfWebApp() {
return InProject.locate("common/src/web");
}
private static File findJsSrcWebAppRoot() {
return InProject.locate("javascript");
}
public String getHostName() {
return hostName;
}
public String getAlternateHostName() {
String alternativeHostnameFromProperty = System.getenv(ALTERNATIVE_HOSTNAME_FOR_TEST_ENV_NAME);
return alternativeHostnameFromProperty == null ?
networkUtils.getPrivateLocalAddress() : alternativeHostnameFromProperty;
}
public String whereIs(String relativeUrl) {
relativeUrl = getMainContextPath(relativeUrl);
return "http://" + getHostName() + ":" + port + relativeUrl;
}
public String whereElseIs(String relativeUrl) {
relativeUrl = getMainContextPath(relativeUrl);
return "http://" + getAlternateHostName() + ":" + port + relativeUrl;
}
public String whereIsSecure(String relativeUrl) {
relativeUrl = getMainContextPath(relativeUrl);
return "https://" + getHostName() + ":" + securePort + relativeUrl;
}
public String whereIsWithCredentials(String relativeUrl, String user, String pass) {
relativeUrl = getMainContextPath(relativeUrl);
return "http://" + user + ":" + pass + "@" + getHostName() + ":" + port + relativeUrl;
}
protected String getMainContextPath(String relativeUrl) {
if (!relativeUrl.startsWith("/")) {
relativeUrl = DEFAULT_CONTEXT_PATH + "/" + relativeUrl;
}
return relativeUrl;
}
public void start() {
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(port);
server.addConnector(connector);
File keyStore = getKeyStore();
if (!keyStore.exists()) {
throw new RuntimeException(
"Cannot find keystore for SSL cert: " + keyStore.getAbsolutePath());
}
SslSocketConnector secureSocket = new SslSocketConnector();
secureSocket.setPort(securePort);
secureSocket.setKeystore(keyStore.getAbsolutePath());
secureSocket.setPassword("password");
secureSocket.setKeyPassword("password");
secureSocket.setTruststore(keyStore.getAbsolutePath());
secureSocket.setTrustPassword("password");
server.addConnector(secureSocket);
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected File getKeyStore() {
return InProject.locate("java/client/test/keystore");
}
public void listenOn(int port) {
this.port = port;
}
public void listenSecurelyOn(int port) {
this.securePort = port;
}
protected void addListener(Connector listener) {
server.addConnector(listener);
}
public void stop() {
try {
server.stop();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void addServlet(String name, String url, Class<? extends Servlet> servletClass) {
addServlet(defaultContext, name, url, servletClass);
}
public void addServlet(WebAppContext context, String name, String url,
Class<? extends Servlet> servletClass) {
try {
context.addServlet(new ServletHolder(servletClass), url);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void addServlet(String url, Servlet servlet) {
defaultContext.addServlet(new ServletHolder(servlet), url);
}
public void addFilter(Class<? extends Filter> filter, String path,
int dispatches) {
defaultContext.addFilter(filter, path, dispatches);
}
protected WebAppContext addWebApplication(String contextPath, File rootDir) {
return addWebApplication(contextPath, rootDir.getAbsolutePath());
}
private WebAppContext addWebApplication(String contextPath, String absolutePath) {
WebAppContext app = new WebAppContext();
app.setContextPath(contextPath);
app.setWar(absolutePath);
app.getMimeTypes().addMimeMapping("qml", "application/qml");
handlers.addHandler(app);
return app;
}
public void addAdditionalWebApplication(String context, String absolutePath) {
addWebApplication(context, absolutePath);
}
public void addHandler(Handler handler) {
handlers.addHandler(handler);
}
private static int getHttpPortFromEnv() {
String port = System.getenv(FIXED_HTTP_PORT_ENV_NAME);
return port == null ? DEFAULT_HTTP_PORT : Integer.parseInt(port);
}
private static int getHttpsPortFromEnv() {
String port = System.getenv(FIXED_HTTPS_PORT_ENV_NAME);
return port == null ? DEFAULT_HTTPS_PORT : Integer.parseInt(port);
}
public static void main(String[] args) {
Jetty7AppServer server = new Jetty7AppServer(detectHostname());
server.listenOn(getHttpPortFromEnv());
System.out.println(String.format("Starting server on port %d", getHttpPortFromEnv()));
server.listenSecurelyOn(getHttpsPortFromEnv());
System.out.println(String.format("HTTPS on %d", getHttpsPortFromEnv()));
server.start();
}
}
| java/client/test/org/openqa/selenium/environment/webserver/Jetty7AppServer.java | /*
Copyright 2012 Software Freedom Conservancy
Copyright 2007-2012 WebDriver committers
Copyright 2007-2009 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.environment.webserver;
import org.openqa.selenium.net.NetworkUtils;
import org.openqa.selenium.testing.InProject;
import org.seleniumhq.jetty7.server.Connector;
import org.seleniumhq.jetty7.server.Handler;
import org.seleniumhq.jetty7.server.Server;
import org.seleniumhq.jetty7.server.handler.ContextHandlerCollection;
import org.seleniumhq.jetty7.server.nio.SelectChannelConnector;
import org.seleniumhq.jetty7.server.ssl.SslSocketConnector;
import org.seleniumhq.jetty7.servlet.ServletHolder;
import org.seleniumhq.jetty7.servlets.MultiPartFilter;
import org.seleniumhq.jetty7.webapp.WebAppContext;
import java.io.File;
import javax.servlet.Filter;
import javax.servlet.Servlet;
import static org.openqa.selenium.net.PortProber.findFreePort;
import static org.openqa.selenium.testing.InProject.locate;
public class Jetty7AppServer implements AppServer {
private static final String HOSTNAME_FOR_TEST_ENV_NAME = "HOSTNAME";
private static final String ALTERNATIVE_HOSTNAME_FOR_TEST_ENV_NAME = "ALTERNATIVE_HOSTNAME";
private static final String FIXED_HTTP_PORT_ENV_NAME = "TEST_HTTP_PORT";
private static final String FIXED_HTTPS_PORT_ENV_NAME = "TEST_HTTPS_PORT";
private static final int DEFAULT_HTTP_PORT = 2310;
private static final int DEFAULT_HTTPS_PORT = 2410;
private static final String DEFAULT_CONTEXT_PATH = "/common";
private static final String JS_SRC_CONTEXT_PATH = "/javascript";
private static final String CLOSURE_CONTEXT_PATH = "/third_party/closure/goog";
private static final String THIRD_PARTY_JS_CONTEXT_PATH = "/third_party/js";
private static final NetworkUtils networkUtils = new NetworkUtils();
private int port;
private int securePort;
private File path;
private File jsSrcRoot;
private final Server server;
private WebAppContext defaultContext;
private WebAppContext jsContext;
private ContextHandlerCollection handlers;
private final String hostName;
public Jetty7AppServer() {
this(detectHostname());
}
public static String detectHostname() {
String hostnameFromProperty = System.getenv(HOSTNAME_FOR_TEST_ENV_NAME);
return hostnameFromProperty == null ? "localhost" : hostnameFromProperty;
}
public Jetty7AppServer(String hostName) {
this.hostName = hostName;
// Be quiet. Unless we want things to be chatty
if (!Boolean.getBoolean("webdriver.debug")) {
new NullLogger().disableLogging();
}
server = new Server();
path = findRootOfWebApp();
jsSrcRoot = findJsSrcWebAppRoot();
handlers = new ContextHandlerCollection();
defaultContext = addWebApplication(DEFAULT_CONTEXT_PATH, path);
jsContext = addWebApplication(JS_SRC_CONTEXT_PATH, jsSrcRoot);
addWebApplication(CLOSURE_CONTEXT_PATH, locate("third_party/closure/goog"));
addWebApplication(THIRD_PARTY_JS_CONTEXT_PATH, locate("third_party/js"));
server.setHandler(handlers);
addServlet("Redirecter", "/redirect", RedirectServlet.class);
addServlet("InfinitePagerServer", "/page/*", PageServlet.class);
addServlet(defaultContext, "Manifest", "/manifest/*", ManifestServlet.class);
addServlet(defaultContext, "Manifest", "*.appcache", ManifestServlet.class);
addServlet(jsContext, "Manifest", "*.appcache", ManifestServlet.class);
// Serves every file under DEFAULT_CONTEXT_PATH/utf8 as UTF-8 to the browser
addServlet(defaultContext, "UTF8", "/utf8/*", Utf8Servlet.class);
addServlet("Uploader", "/upload", UploadServlet.class);
addServlet("Unusual encoding", "/encoding", EncodingServlet.class);
addServlet("Sleeper", "/sleep", SleepingServlet.class);
addServlet("Kill switch", "/quitquitquit", KillSwitchServlet.class);
addServlet("Basic Authentication", "/basicAuth", BasicAuth.class);
addFilter(MultiPartFilter.class, "/upload", 0 /* DEFAULT dispatches */);
listenOn(getHttpPort());
listenSecurelyOn(getHttpsPort());
}
private int getHttpPort() {
String port = System.getenv(FIXED_HTTP_PORT_ENV_NAME);
return port == null ? findFreePort() : Integer.parseInt(port);
}
private int getHttpsPort() {
String port = System.getenv(FIXED_HTTPS_PORT_ENV_NAME);
return port == null ? findFreePort() : Integer.parseInt(port);
}
protected File findRootOfWebApp() {
return InProject.locate("common/src/web");
}
private static File findJsSrcWebAppRoot() {
return InProject.locate("javascript");
}
public String getHostName() {
return hostName;
}
public String getAlternateHostName() {
String alternativeHostnameFromProperty = System.getenv(ALTERNATIVE_HOSTNAME_FOR_TEST_ENV_NAME);
return alternativeHostnameFromProperty == null ?
networkUtils.getPrivateLocalAddress() : alternativeHostnameFromProperty;
}
public String whereIs(String relativeUrl) {
relativeUrl = getMainContextPath(relativeUrl);
return "http://" + getHostName() + ":" + port + relativeUrl;
}
public String whereElseIs(String relativeUrl) {
relativeUrl = getMainContextPath(relativeUrl);
return "http://" + getAlternateHostName() + ":" + port + relativeUrl;
}
public String whereIsSecure(String relativeUrl) {
relativeUrl = getMainContextPath(relativeUrl);
return "https://" + getHostName() + ":" + securePort + relativeUrl;
}
public String whereIsWithCredentials(String relativeUrl, String user, String pass) {
relativeUrl = getMainContextPath(relativeUrl);
return "http://" + user + ":" + pass + "@" + getHostName() + ":" + port + relativeUrl;
}
protected String getMainContextPath(String relativeUrl) {
if (!relativeUrl.startsWith("/")) {
relativeUrl = DEFAULT_CONTEXT_PATH + "/" + relativeUrl;
}
return relativeUrl;
}
public void start() {
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(port);
server.addConnector(connector);
File keyStore = getKeyStore();
if (!keyStore.exists()) {
throw new RuntimeException(
"Cannot find keystore for SSL cert: " + keyStore.getAbsolutePath());
}
SslSocketConnector secureSocket = new SslSocketConnector();
secureSocket.setPort(securePort);
secureSocket.setKeystore(keyStore.getAbsolutePath());
secureSocket.setPassword("password");
secureSocket.setKeyPassword("password");
secureSocket.setTruststore(keyStore.getAbsolutePath());
secureSocket.setTrustPassword("password");
server.addConnector(secureSocket);
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected File getKeyStore() {
return InProject.locate("java/client/test/keystore");
}
public void listenOn(int port) {
this.port = port;
}
public void listenSecurelyOn(int port) {
this.securePort = port;
}
protected void addListener(Connector listener) {
server.addConnector(listener);
}
public void stop() {
try {
server.stop();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void addServlet(String name, String url, Class<? extends Servlet> servletClass) {
addServlet(defaultContext, name, url, servletClass);
}
public void addServlet(WebAppContext context, String name, String url,
Class<? extends Servlet> servletClass) {
try {
context.addServlet(new ServletHolder(servletClass), url);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void addServlet(String url, Servlet servlet) {
defaultContext.addServlet(new ServletHolder(servlet), url);
}
public void addFilter(Class<? extends Filter> filter, String path,
int dispatches) {
defaultContext.addFilter(filter, path, dispatches);
}
protected WebAppContext addWebApplication(String contextPath, File rootDir) {
return addWebApplication(contextPath, rootDir.getAbsolutePath());
}
private WebAppContext addWebApplication(String contextPath, String absolutePath) {
WebAppContext app = new WebAppContext();
app.setContextPath(contextPath);
app.setWar(absolutePath);
handlers.addHandler(app);
return app;
}
public void addAdditionalWebApplication(String context, String absolutePath) {
addWebApplication(context, absolutePath);
}
public void addHandler(Handler handler) {
handlers.addHandler(handler);
}
private static int getHttpPortFromEnv() {
String port = System.getenv(FIXED_HTTP_PORT_ENV_NAME);
return port == null ? DEFAULT_HTTP_PORT : Integer.parseInt(port);
}
private static int getHttpsPortFromEnv() {
String port = System.getenv(FIXED_HTTPS_PORT_ENV_NAME);
return port == null ? DEFAULT_HTTPS_PORT : Integer.parseInt(port);
}
public static void main(String[] args) {
Jetty7AppServer server = new Jetty7AppServer(detectHostname());
server.listenOn(getHttpPortFromEnv());
System.out.println(String.format("Starting server on port %d", getHttpPortFromEnv()));
server.listenSecurelyOn(getHttpsPortFromEnv());
System.out.println(String.format("HTTPS on %d", getHttpsPortFromEnv()));
server.start();
}
}
| added qml content type to internal web serveR
| java/client/test/org/openqa/selenium/environment/webserver/Jetty7AppServer.java | added qml content type to internal web serveR | <ide><path>ava/client/test/org/openqa/selenium/environment/webserver/Jetty7AppServer.java
<ide> WebAppContext app = new WebAppContext();
<ide> app.setContextPath(contextPath);
<ide> app.setWar(absolutePath);
<add> app.getMimeTypes().addMimeMapping("qml", "application/qml");
<ide> handlers.addHandler(app);
<ide> return app;
<ide> } |
|
Java | apache-2.0 | b6d4c3e86d27e6f19d168ffdd8335569aa5cb63d | 0 | wido/cloudstack,argv0/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,mufaddalq/cloudstack-datera-driver,DaanHoogland/cloudstack,resmo/cloudstack,wido/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,cinderella/incubator-cloudstack,argv0/cloudstack,mufaddalq/cloudstack-datera-driver,argv0/cloudstack,wido/cloudstack,mufaddalq/cloudstack-datera-driver,jcshen007/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,cinderella/incubator-cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,jcshen007/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,cinderella/incubator-cloudstack,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,jcshen007/cloudstack,cinderella/incubator-cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,resmo/cloudstack,cinderella/incubator-cloudstack,GabrielBrascher/cloudstack,mufaddalq/cloudstack-datera-driver,argv0/cloudstack,argv0/cloudstack,wido/cloudstack,argv0/cloudstack,jcshen007/cloudstack,resmo/cloudstack | /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.storage.snapshot;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.ApiDispatcher;
import com.cloud.api.ApiGsonHelper;
import com.cloud.api.commands.CreateSnapshotCmd;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.dao.AsyncJobDao;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.event.EventTypes;
import com.cloud.event.EventUtils;
import com.cloud.storage.Snapshot;
import com.cloud.storage.SnapshotPolicyVO;
import com.cloud.storage.SnapshotScheduleVO;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.SnapshotPolicyDao;
import com.cloud.storage.dao.SnapshotScheduleDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.DateUtil;
import com.cloud.utils.DateUtil.IntervalType;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.concurrency.TestClock;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.SearchCriteria;
/**
*
*/
@Local(value={SnapshotScheduler.class})
public class SnapshotSchedulerImpl implements SnapshotScheduler {
private static final Logger s_logger = Logger.getLogger(SnapshotSchedulerImpl.class);
private String _name = null;
@Inject protected AsyncJobDao _asyncJobDao;
@Inject protected SnapshotDao _snapshotDao;
@Inject protected SnapshotScheduleDao _snapshotScheduleDao;
@Inject protected SnapshotPolicyDao _snapshotPolicyDao;
@Inject protected AsyncJobManager _asyncMgr;
@Inject protected SnapshotManager _snapshotManager;
@Inject protected StoragePoolHostDao _poolHostDao;
@Inject protected VolumeDao _volsDao;
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds
private int _snapshotPollInterval;
private Timer _testClockTimer;
private Date _currentTimestamp;
private TestClock _testTimerTask;
private Date getNextScheduledTime(long policyId, Date currentTimestamp) {
SnapshotPolicyVO policy = _snapshotPolicyDao.findById(policyId);
Date nextTimestamp = null;
if (policy != null) {
short intervalType = policy.getInterval();
IntervalType type = DateUtil.getIntervalType(intervalType);
String schedule = policy.getSchedule();
String timezone = policy.getTimezone();
nextTimestamp = DateUtil.getNextRunTime(type, schedule, timezone, currentTimestamp);
String currentTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, currentTimestamp);
String nextScheduledTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, nextTimestamp);
s_logger.debug("Current time is " + currentTime + ". NextScheduledTime of policyId " + policyId + " is " + nextScheduledTime);
}
return nextTimestamp;
}
/**
* {@inheritDoc}
*/
@Override
public void poll(Date currentTimestamp) {
// We don't maintain the time. The timer task does.
_currentTimestamp = currentTimestamp;
GlobalLock scanLock = GlobalLock.getInternLock("snapshot.poll");
try {
if(scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) {
try {
checkStatusOfCurrentlyExecutingSnapshots();
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
scanLock = GlobalLock.getInternLock("snapshot.poll");
try {
if(scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) {
try {
scheduleSnapshots();
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
}
private void checkStatusOfCurrentlyExecutingSnapshots() {
SearchCriteria<SnapshotScheduleVO> sc = _snapshotScheduleDao.createSearchCriteria();
sc.addAnd("asyncJobId", SearchCriteria.Op.NNULL);
List<SnapshotScheduleVO> snapshotSchedules = _snapshotScheduleDao.search(sc, null);
for (SnapshotScheduleVO snapshotSchedule : snapshotSchedules) {
Long asyncJobId = snapshotSchedule.getAsyncJobId();
AsyncJobVO asyncJob = _asyncJobDao.findById(asyncJobId);
switch (asyncJob.getStatus()) {
case AsyncJobResult.STATUS_SUCCEEDED:
// The snapshot has been successfully backed up.
// The snapshot state has also been cleaned up.
// We can schedule the next job for this snapshot.
// Remove the existing entry in the snapshot_schedule table.
scheduleNextSnapshotJob(snapshotSchedule);
break;
case AsyncJobResult.STATUS_FAILED:
// Check the snapshot status.
Long snapshotId = snapshotSchedule.getSnapshotId();
if (snapshotId == null) {
// createSnapshotAsync exited, successfully or unsuccessfully,
// even before creating a snapshot record
// No cleanup needs to be done.
// Schedule the next snapshot.
scheduleNextSnapshotJob(snapshotSchedule);
}
else {
SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
if (snapshot == null || snapshot.getRemoved() != null) {
// This snapshot has been deleted successfully from the primary storage
// Again no cleanup needs to be done.
// Schedule the next snapshot.
// There's very little probability that the code reaches this point.
// The snapshotId is a foreign key for the snapshot_schedule table
// set to ON DELETE CASCADE. So if the snapshot entry is deleted, the snapshot_schedule entry will be too.
// But what if it has only been marked as removed?
scheduleNextSnapshotJob(snapshotSchedule);
}
else {
// The management server executing this snapshot job appears to have crashed
// while creating the snapshot on primary storage/or backing it up.
// We have no idea whether the snapshot was successfully taken on the primary or not.
// Schedule the next snapshot job.
// The ValidatePreviousSnapshotCommand will take appropriate action on this snapshot
// If the snapshot was taken successfully on primary, it will retry backing it up.
// and cleanup the previous snapshot
// Set the userId to that of system.
//_snapshotManager.validateSnapshot(1L, snapshot);
// In all cases, schedule the next snapshot job
scheduleNextSnapshotJob(snapshotSchedule);
}
}
break;
case AsyncJobResult.STATUS_IN_PROGRESS:
// There is no way of knowing from here whether
// 1) Another management server is processing this snapshot job
// 2) The management server has crashed and this snapshot is lying
// around in an inconsistent state.
// Hopefully, this can be resolved at the backend when the current snapshot gets executed.
// But if it remains in this state, the current snapshot will not get executed.
// And it will remain in stasis.
break;
}
}
}
@DB
protected void scheduleSnapshots() {
String displayTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, _currentTimestamp);
s_logger.debug("Snapshot scheduler.poll is being called at " + displayTime);
List<SnapshotScheduleVO> snapshotsToBeExecuted = _snapshotScheduleDao.getSchedulesToExecute(_currentTimestamp);
s_logger.debug("Got " + snapshotsToBeExecuted.size() + " snapshots to be executed at " + displayTime);
// This is done for recurring snapshots, which are executed by the system automatically
// Hence set user id to that of system
long userId = 1;
for (SnapshotScheduleVO snapshotToBeExecuted : snapshotsToBeExecuted) {
SnapshotScheduleVO tmpSnapshotScheduleVO = null;
long snapshotScheId = snapshotToBeExecuted.getId();
long policyId = snapshotToBeExecuted.getPolicyId();
long volumeId = snapshotToBeExecuted.getVolumeId();
try {
VolumeVO volume = _volsDao.findById(volumeId);
if ( volume.getPoolId() == null) {
// this volume is not attached
continue;
}
if ( _snapshotPolicyDao.findById(policyId) == null ) {
_snapshotScheduleDao.remove(snapshotToBeExecuted.getId());
}
if (s_logger.isDebugEnabled()) {
Date scheduledTimestamp = snapshotToBeExecuted.getScheduledTimestamp();
displayTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, scheduledTimestamp);
s_logger.debug("Scheduling 1 snapshot for volume " + volumeId + " for schedule id: "
+ snapshotToBeExecuted.getId() + " at " + displayTime);
}
tmpSnapshotScheduleVO = _snapshotScheduleDao.acquireInLockTable(snapshotScheId);
Long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM,
EventTypes.EVENT_SNAPSHOT_CREATE, "creating snapshot for volume Id:"+volumeId,0);
Map<String, String> params = new HashMap<String, String>();
params.put("volumeid", ""+volumeId);
params.put("policyid", ""+policyId);
params.put("ctxUserId", "1");
params.put("ctxAccountId", "1");
params.put("ctxStartEventId", String.valueOf(eventId));
CreateSnapshotCmd cmd = new CreateSnapshotCmd();
ApiDispatcher.getInstance().dispatchCreateCmd(cmd, params);
params.put("id", ""+cmd.getEntityId());
params.put("ctxStartEventId", "1");
AsyncJobVO job = new AsyncJobVO();
job.setUserId(userId);
// Just have SYSTEM own the job for now. Users won't be able to see this job, but
// it's an internal job so probably not a huge deal.
job.setAccountId(1L);
job.setCmd(CreateSnapshotCmd.class.getName());
job.setInstanceId(cmd.getEntityId());
job.setCmdInfo(ApiGsonHelper.getBuilder().create().toJson(params));
long jobId = _asyncMgr.submitAsyncJob(job);
tmpSnapshotScheduleVO.setAsyncJobId(jobId);
_snapshotScheduleDao.update(snapshotScheId, tmpSnapshotScheduleVO);
} catch (Exception e) {
s_logger.debug("Scheduling snapshot failed due to " + e.toString(), e);
} finally {
if ( tmpSnapshotScheduleVO != null) {
_snapshotScheduleDao.releaseFromLockTable(snapshotScheId);
}
}
}
}
private Date scheduleNextSnapshotJob(SnapshotScheduleVO snapshotSchedule) {
if ( snapshotSchedule == null ) {
return null;
}
Long policyId = snapshotSchedule.getPolicyId();
if (policyId.longValue() == Snapshot.MANUAL_POLICY_ID) {
// Don't need to schedule the next job for this.
return null;
}
SnapshotPolicyVO snapshotPolicy = _snapshotPolicyDao.findById(policyId);
if ( snapshotPolicy == null ) {
_snapshotScheduleDao.expunge(snapshotSchedule.getId());
}
return scheduleNextSnapshotJob(snapshotPolicy);
}
@Override @DB
public Date scheduleNextSnapshotJob(SnapshotPolicyVO policy) {
if ( policy == null) {
return null;
}
long policyId = policy.getId();
if ( policyId == Snapshot.MANUAL_POLICY_ID ) {
return null;
}
Date nextSnapshotTimestamp = getNextScheduledTime(policyId, _currentTimestamp);
SnapshotScheduleVO spstSchedVO = _snapshotScheduleDao.findOneByVolumePolicy(policy.getVolumeId(), policy.getId());
if ( spstSchedVO == null ) {
spstSchedVO = new SnapshotScheduleVO(policy.getVolumeId(), policyId, nextSnapshotTimestamp);
_snapshotScheduleDao.persist(spstSchedVO);
} else {
try{
spstSchedVO = _snapshotScheduleDao.acquireInLockTable(spstSchedVO.getId());
spstSchedVO.setPolicyId(policyId);
spstSchedVO.setScheduledTimestamp(nextSnapshotTimestamp);
spstSchedVO.setAsyncJobId(null);
spstSchedVO.setSnapshotId(null);
_snapshotScheduleDao.update(spstSchedVO.getId(), spstSchedVO);
} finally {
if(spstSchedVO != null ) {
_snapshotScheduleDao.releaseFromLockTable(spstSchedVO.getId());
}
}
}
return nextSnapshotTimestamp;
}
@Override @DB
public boolean removeSchedule(Long volumeId, Long policyId) {
// We can only remove schedules which are in the future. Not which are already executed in the past.
SnapshotScheduleVO schedule = _snapshotScheduleDao.getCurrentSchedule(volumeId, policyId, false);
boolean success = true;
if (schedule != null) {
success = _snapshotScheduleDao.remove(schedule.getId());
}
if(!success){
s_logger.debug("Error while deleting Snapshot schedule with Id: "+schedule.getId());
}
return success;
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
_name = name;
ComponentLocator locator = ComponentLocator.getCurrentLocator();
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
if (configDao == null) {
s_logger.error("Unable to get the configuration dao. " + ConfigurationDao.class.getName());
return false;
}
_snapshotPollInterval = NumbersUtil.parseInt(configDao.getValue("snapshot.poll.interval"), 300);
boolean snapshotsRecurringTest = Boolean.parseBoolean(configDao.getValue("snapshot.recurring.test"));
if (snapshotsRecurringTest) {
// look for some test values in the configuration table so that snapshots can be taken more frequently (QA test code)
int minutesPerHour = NumbersUtil.parseInt(configDao.getValue("snapshot.test.minutes.per.hour"), 60);
int hoursPerDay = NumbersUtil.parseInt(configDao.getValue("snapshot.test.hours.per.day"), 24);
int daysPerWeek = NumbersUtil.parseInt(configDao.getValue("snapshot.test.days.per.week"), 7);
int daysPerMonth = NumbersUtil.parseInt(configDao.getValue("snapshot.test.days.per.month"), 30);
int weeksPerMonth = NumbersUtil.parseInt(configDao.getValue("snapshot.test.weeks.per.month"), 4);
int monthsPerYear = NumbersUtil.parseInt(configDao.getValue("snapshot.test.months.per.year"), 12);
_testTimerTask = new TestClock(this, minutesPerHour, hoursPerDay, daysPerWeek, daysPerMonth, weeksPerMonth, monthsPerYear);
}
_currentTimestamp = new Date();
s_logger.info("Snapshot Scheduler is configured.");
return true;
}
@Override
public String getName() {
return _name;
}
@Override @DB
public boolean start() {
// reschedule all policies after management restart
List<SnapshotPolicyVO> policyInstances = _snapshotPolicyDao.listAll();
for( SnapshotPolicyVO policyInstance : policyInstances) {
if( policyInstance.getId() != Snapshot.MANUAL_POLICY_ID ) {
scheduleNextSnapshotJob(policyInstance);
}
}
if (_testTimerTask != null) {
_testClockTimer = new Timer("TestClock");
// Run the test clock every 60s. Because every tick is counted as 1 minute.
// Else it becomes too confusing.
_testClockTimer.schedule(_testTimerTask, 100*1000L, 60*1000L);
}
else {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
try {
Date currentTimestamp = new Date();
poll(currentTimestamp);
} catch (Throwable t) {
s_logger.warn("Catch throwable in snapshot scheduler " + t.toString(), t);
}
}
};
_testClockTimer = new Timer("SnapshotPollTask");
_testClockTimer.schedule(timerTask, _snapshotPollInterval*1000L, _snapshotPollInterval*1000L);
}
return true;
}
@Override
public boolean stop() {
return true;
}
}
| server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java | /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.storage.snapshot;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.ApiDispatcher;
import com.cloud.api.ApiGsonHelper;
import com.cloud.api.commands.CreateSnapshotCmd;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.dao.AsyncJobDao;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.event.EventTypes;
import com.cloud.event.EventUtils;
import com.cloud.storage.Snapshot;
import com.cloud.storage.SnapshotPolicyVO;
import com.cloud.storage.SnapshotScheduleVO;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.SnapshotPolicyDao;
import com.cloud.storage.dao.SnapshotScheduleDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.DateUtil;
import com.cloud.utils.DateUtil.IntervalType;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.concurrency.TestClock;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.SearchCriteria;
/**
*
*/
@Local(value={SnapshotScheduler.class})
public class SnapshotSchedulerImpl implements SnapshotScheduler {
private static final Logger s_logger = Logger.getLogger(SnapshotSchedulerImpl.class);
private String _name = null;
@Inject protected AsyncJobDao _asyncJobDao;
@Inject protected SnapshotDao _snapshotDao;
@Inject protected SnapshotScheduleDao _snapshotScheduleDao;
@Inject protected SnapshotPolicyDao _snapshotPolicyDao;
@Inject protected AsyncJobManager _asyncMgr;
@Inject protected SnapshotManager _snapshotManager;
@Inject protected StoragePoolHostDao _poolHostDao;
@Inject protected VolumeDao _volsDao;
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds
private int _snapshotPollInterval;
private Timer _testClockTimer;
private Date _currentTimestamp;
private TestClock _testTimerTask;
private Date getNextScheduledTime(long policyId, Date currentTimestamp) {
SnapshotPolicyVO policy = _snapshotPolicyDao.findById(policyId);
Date nextTimestamp = null;
if (policy != null) {
short intervalType = policy.getInterval();
IntervalType type = DateUtil.getIntervalType(intervalType);
String schedule = policy.getSchedule();
String timezone = policy.getTimezone();
nextTimestamp = DateUtil.getNextRunTime(type, schedule, timezone, currentTimestamp);
String currentTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, currentTimestamp);
String nextScheduledTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, nextTimestamp);
s_logger.debug("Current time is " + currentTime + ". NextScheduledTime of policyId " + policyId + " is " + nextScheduledTime);
}
return nextTimestamp;
}
/**
* {@inheritDoc}
*/
@Override
public void poll(Date currentTimestamp) {
// We don't maintain the time. The timer task does.
_currentTimestamp = currentTimestamp;
GlobalLock scanLock = GlobalLock.getInternLock("snapshot.poll");
try {
if(scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) {
try {
checkStatusOfCurrentlyExecutingSnapshots();
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
scanLock = GlobalLock.getInternLock("snapshot.poll");
try {
if(scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) {
try {
scheduleSnapshots();
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
}
private void checkStatusOfCurrentlyExecutingSnapshots() {
SearchCriteria<SnapshotScheduleVO> sc = _snapshotScheduleDao.createSearchCriteria();
sc.addAnd("asyncJobId", SearchCriteria.Op.NNULL);
List<SnapshotScheduleVO> snapshotSchedules = _snapshotScheduleDao.search(sc, null);
for (SnapshotScheduleVO snapshotSchedule : snapshotSchedules) {
Long asyncJobId = snapshotSchedule.getAsyncJobId();
AsyncJobVO asyncJob = _asyncJobDao.findById(asyncJobId);
switch (asyncJob.getStatus()) {
case AsyncJobResult.STATUS_SUCCEEDED:
// The snapshot has been successfully backed up.
// The snapshot state has also been cleaned up.
// We can schedule the next job for this snapshot.
// Remove the existing entry in the snapshot_schedule table.
scheduleNextSnapshotJob(snapshotSchedule);
break;
case AsyncJobResult.STATUS_FAILED:
// Check the snapshot status.
Long snapshotId = snapshotSchedule.getSnapshotId();
if (snapshotId == null) {
// createSnapshotAsync exited, successfully or unsuccessfully,
// even before creating a snapshot record
// No cleanup needs to be done.
// Schedule the next snapshot.
scheduleNextSnapshotJob(snapshotSchedule);
}
else {
SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
if (snapshot == null || snapshot.getRemoved() != null) {
// This snapshot has been deleted successfully from the primary storage
// Again no cleanup needs to be done.
// Schedule the next snapshot.
// There's very little probability that the code reaches this point.
// The snapshotId is a foreign key for the snapshot_schedule table
// set to ON DELETE CASCADE. So if the snapshot entry is deleted, the snapshot_schedule entry will be too.
// But what if it has only been marked as removed?
scheduleNextSnapshotJob(snapshotSchedule);
}
else {
// The management server executing this snapshot job appears to have crashed
// while creating the snapshot on primary storage/or backing it up.
// We have no idea whether the snapshot was successfully taken on the primary or not.
// Schedule the next snapshot job.
// The ValidatePreviousSnapshotCommand will take appropriate action on this snapshot
// If the snapshot was taken successfully on primary, it will retry backing it up.
// and cleanup the previous snapshot
// Set the userId to that of system.
//_snapshotManager.validateSnapshot(1L, snapshot);
// In all cases, schedule the next snapshot job
scheduleNextSnapshotJob(snapshotSchedule);
}
}
break;
case AsyncJobResult.STATUS_IN_PROGRESS:
// There is no way of knowing from here whether
// 1) Another management server is processing this snapshot job
// 2) The management server has crashed and this snapshot is lying
// around in an inconsistent state.
// Hopefully, this can be resolved at the backend when the current snapshot gets executed.
// But if it remains in this state, the current snapshot will not get executed.
// And it will remain in stasis.
break;
}
}
}
@DB
protected void scheduleSnapshots() {
String displayTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, _currentTimestamp);
s_logger.debug("Snapshot scheduler.poll is being called at " + displayTime);
List<SnapshotScheduleVO> snapshotsToBeExecuted = _snapshotScheduleDao.getSchedulesToExecute(_currentTimestamp);
s_logger.debug("Got " + snapshotsToBeExecuted.size() + " snapshots to be executed at " + displayTime);
// This is done for recurring snapshots, which are executed by the system automatically
// Hence set user id to that of system
long userId = 1;
for (SnapshotScheduleVO snapshotToBeExecuted : snapshotsToBeExecuted) {
long policyId = snapshotToBeExecuted.getPolicyId();
long volumeId = snapshotToBeExecuted.getVolumeId();
VolumeVO volume = _volsDao.findById(volumeId);
if ( volume.getPoolId() == null) {
// this volume is not attached
continue;
}
if ( _snapshotPolicyDao.findById(policyId) == null ) {
_snapshotScheduleDao.remove(snapshotToBeExecuted.getId());
}
if (s_logger.isDebugEnabled()) {
Date scheduledTimestamp = snapshotToBeExecuted.getScheduledTimestamp();
displayTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, scheduledTimestamp);
s_logger.debug("Scheduling 1 snapshot for volume " + volumeId + " for schedule id: "
+ snapshotToBeExecuted.getId() + " at " + displayTime);
}
long snapshotScheId = snapshotToBeExecuted.getId();
SnapshotScheduleVO tmpSnapshotScheduleVO = null;
try {
tmpSnapshotScheduleVO = _snapshotScheduleDao.acquireInLockTable(snapshotScheId);
Long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM,
EventTypes.EVENT_SNAPSHOT_CREATE, "creating snapshot for volume Id:"+volumeId,0);
Map<String, String> params = new HashMap<String, String>();
params.put("volumeid", ""+volumeId);
params.put("policyid", ""+policyId);
params.put("ctxUserId", "1");
params.put("ctxAccountId", "1");
params.put("ctxStartEventId", String.valueOf(eventId));
CreateSnapshotCmd cmd = new CreateSnapshotCmd();
ApiDispatcher.getInstance().dispatchCreateCmd(cmd, params);
params.put("id", ""+cmd.getEntityId());
params.put("ctxStartEventId", "1");
AsyncJobVO job = new AsyncJobVO();
job.setUserId(userId);
// Just have SYSTEM own the job for now. Users won't be able to see this job, but
// it's an internal job so probably not a huge deal.
job.setAccountId(1L);
job.setCmd(CreateSnapshotCmd.class.getName());
job.setInstanceId(cmd.getEntityId());
job.setCmdInfo(ApiGsonHelper.getBuilder().create().toJson(params));
long jobId = _asyncMgr.submitAsyncJob(job);
tmpSnapshotScheduleVO.setAsyncJobId(jobId);
_snapshotScheduleDao.update(snapshotScheId, tmpSnapshotScheduleVO);
} catch (Exception e) {
s_logger.debug("Scheduling snapshot failed due to " + e.toString(), e);
} finally {
if (tmpSnapshotScheduleVO != null) {
_snapshotScheduleDao.releaseFromLockTable(snapshotScheId);
}
}
}
}
private Date scheduleNextSnapshotJob(SnapshotScheduleVO snapshotSchedule) {
if ( snapshotSchedule == null ) {
return null;
}
Long policyId = snapshotSchedule.getPolicyId();
if (policyId.longValue() == Snapshot.MANUAL_POLICY_ID) {
// Don't need to schedule the next job for this.
return null;
}
SnapshotPolicyVO snapshotPolicy = _snapshotPolicyDao.findById(policyId);
if ( snapshotPolicy == null ) {
_snapshotScheduleDao.expunge(snapshotSchedule.getId());
}
return scheduleNextSnapshotJob(snapshotPolicy);
}
@Override @DB
public Date scheduleNextSnapshotJob(SnapshotPolicyVO policy) {
if ( policy == null) {
return null;
}
long policyId = policy.getId();
if ( policyId == Snapshot.MANUAL_POLICY_ID ) {
return null;
}
Date nextSnapshotTimestamp = getNextScheduledTime(policyId, _currentTimestamp);
SnapshotScheduleVO spstSchedVO = _snapshotScheduleDao.findOneByVolumePolicy(policy.getVolumeId(), policy.getId());
if ( spstSchedVO == null ) {
spstSchedVO = new SnapshotScheduleVO(policy.getVolumeId(), policyId, nextSnapshotTimestamp);
_snapshotScheduleDao.persist(spstSchedVO);
} else {
try{
spstSchedVO = _snapshotScheduleDao.acquireInLockTable(spstSchedVO.getId());
spstSchedVO.setPolicyId(policyId);
spstSchedVO.setScheduledTimestamp(nextSnapshotTimestamp);
spstSchedVO.setAsyncJobId(null);
spstSchedVO.setSnapshotId(null);
_snapshotScheduleDao.update(spstSchedVO.getId(), spstSchedVO);
} finally {
if(spstSchedVO != null ) {
_snapshotScheduleDao.releaseFromLockTable(spstSchedVO.getId());
}
}
}
return nextSnapshotTimestamp;
}
@Override @DB
public boolean removeSchedule(Long volumeId, Long policyId) {
// We can only remove schedules which are in the future. Not which are already executed in the past.
SnapshotScheduleVO schedule = _snapshotScheduleDao.getCurrentSchedule(volumeId, policyId, false);
boolean success = true;
if (schedule != null) {
success = _snapshotScheduleDao.remove(schedule.getId());
}
if(!success){
s_logger.debug("Error while deleting Snapshot schedule with Id: "+schedule.getId());
}
return success;
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
_name = name;
ComponentLocator locator = ComponentLocator.getCurrentLocator();
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
if (configDao == null) {
s_logger.error("Unable to get the configuration dao. " + ConfigurationDao.class.getName());
return false;
}
_snapshotPollInterval = NumbersUtil.parseInt(configDao.getValue("snapshot.poll.interval"), 300);
boolean snapshotsRecurringTest = Boolean.parseBoolean(configDao.getValue("snapshot.recurring.test"));
if (snapshotsRecurringTest) {
// look for some test values in the configuration table so that snapshots can be taken more frequently (QA test code)
int minutesPerHour = NumbersUtil.parseInt(configDao.getValue("snapshot.test.minutes.per.hour"), 60);
int hoursPerDay = NumbersUtil.parseInt(configDao.getValue("snapshot.test.hours.per.day"), 24);
int daysPerWeek = NumbersUtil.parseInt(configDao.getValue("snapshot.test.days.per.week"), 7);
int daysPerMonth = NumbersUtil.parseInt(configDao.getValue("snapshot.test.days.per.month"), 30);
int weeksPerMonth = NumbersUtil.parseInt(configDao.getValue("snapshot.test.weeks.per.month"), 4);
int monthsPerYear = NumbersUtil.parseInt(configDao.getValue("snapshot.test.months.per.year"), 12);
_testTimerTask = new TestClock(this, minutesPerHour, hoursPerDay, daysPerWeek, daysPerMonth, weeksPerMonth, monthsPerYear);
}
_currentTimestamp = new Date();
s_logger.info("Snapshot Scheduler is configured.");
return true;
}
@Override
public String getName() {
return _name;
}
@Override @DB
public boolean start() {
// reschedule all policies after management restart
List<SnapshotPolicyVO> policyInstances = _snapshotPolicyDao.listAll();
for( SnapshotPolicyVO policyInstance : policyInstances) {
if( policyInstance.getId() != Snapshot.MANUAL_POLICY_ID ) {
scheduleNextSnapshotJob(policyInstance);
}
}
if (_testTimerTask != null) {
_testClockTimer = new Timer("TestClock");
// Run the test clock every 60s. Because every tick is counted as 1 minute.
// Else it becomes too confusing.
_testClockTimer.schedule(_testTimerTask, 100*1000L, 60*1000L);
}
else {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
try {
Date currentTimestamp = new Date();
poll(currentTimestamp);
} catch (Throwable t) {
s_logger.warn("Catch throwable in snapshot scheduler " + t.toString(), t);
}
}
};
_testClockTimer = new Timer("SnapshotPollTask");
_testClockTimer.schedule(timerTask, _snapshotPollInterval*1000L, _snapshotPollInterval*1000L);
}
return true;
}
@Override
public boolean stop() {
return true;
}
}
| bug 10691: expand try-catch, and add more log
| server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java | bug 10691: expand try-catch, and add more log | <ide><path>erver/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java
<ide> long userId = 1;
<ide>
<ide> for (SnapshotScheduleVO snapshotToBeExecuted : snapshotsToBeExecuted) {
<add> SnapshotScheduleVO tmpSnapshotScheduleVO = null;
<add> long snapshotScheId = snapshotToBeExecuted.getId();
<ide> long policyId = snapshotToBeExecuted.getPolicyId();
<ide> long volumeId = snapshotToBeExecuted.getVolumeId();
<del> VolumeVO volume = _volsDao.findById(volumeId);
<del> if ( volume.getPoolId() == null) {
<del> // this volume is not attached
<del> continue;
<del> }
<del> if ( _snapshotPolicyDao.findById(policyId) == null ) {
<del> _snapshotScheduleDao.remove(snapshotToBeExecuted.getId());
<del> }
<del> if (s_logger.isDebugEnabled()) {
<del> Date scheduledTimestamp = snapshotToBeExecuted.getScheduledTimestamp();
<del> displayTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, scheduledTimestamp);
<del> s_logger.debug("Scheduling 1 snapshot for volume " + volumeId + " for schedule id: "
<del> + snapshotToBeExecuted.getId() + " at " + displayTime);
<del> }
<del> long snapshotScheId = snapshotToBeExecuted.getId();
<del> SnapshotScheduleVO tmpSnapshotScheduleVO = null;
<ide> try {
<add> VolumeVO volume = _volsDao.findById(volumeId);
<add> if ( volume.getPoolId() == null) {
<add> // this volume is not attached
<add> continue;
<add> }
<add> if ( _snapshotPolicyDao.findById(policyId) == null ) {
<add> _snapshotScheduleDao.remove(snapshotToBeExecuted.getId());
<add> }
<add> if (s_logger.isDebugEnabled()) {
<add> Date scheduledTimestamp = snapshotToBeExecuted.getScheduledTimestamp();
<add> displayTime = DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, scheduledTimestamp);
<add> s_logger.debug("Scheduling 1 snapshot for volume " + volumeId + " for schedule id: "
<add> + snapshotToBeExecuted.getId() + " at " + displayTime);
<add> }
<add>
<add>
<add>
<ide> tmpSnapshotScheduleVO = _snapshotScheduleDao.acquireInLockTable(snapshotScheId);
<del>
<ide> Long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM,
<ide> EventTypes.EVENT_SNAPSHOT_CREATE, "creating snapshot for volume Id:"+volumeId,0);
<ide>
<ide> } catch (Exception e) {
<ide> s_logger.debug("Scheduling snapshot failed due to " + e.toString(), e);
<ide> } finally {
<del> if (tmpSnapshotScheduleVO != null) {
<add> if ( tmpSnapshotScheduleVO != null) {
<ide> _snapshotScheduleDao.releaseFromLockTable(snapshotScheId);
<ide> }
<ide> } |
|
Java | apache-2.0 | 467ae9090787dfcc75cca252405bb83aac4d1c9c | 0 | Fabryprog/camel,nikhilvibhav/camel,apache/camel,davidkarlsen/camel,tdiesler/camel,punkhorn/camel-upstream,punkhorn/camel-upstream,nicolaferraro/camel,pax95/camel,tadayosi/camel,zregvart/camel,cunningt/camel,nikhilvibhav/camel,tadayosi/camel,ullgren/camel,DariusX/camel,cunningt/camel,apache/camel,CodeSmell/camel,gnodet/camel,cunningt/camel,davidkarlsen/camel,adessaigne/camel,adessaigne/camel,pmoerenhout/camel,pax95/camel,punkhorn/camel-upstream,objectiser/camel,adessaigne/camel,zregvart/camel,tdiesler/camel,gnodet/camel,CodeSmell/camel,pmoerenhout/camel,DariusX/camel,tadayosi/camel,adessaigne/camel,gnodet/camel,zregvart/camel,ullgren/camel,tdiesler/camel,cunningt/camel,tadayosi/camel,adessaigne/camel,tdiesler/camel,ullgren/camel,zregvart/camel,punkhorn/camel-upstream,pax95/camel,alvinkwekel/camel,apache/camel,cunningt/camel,davidkarlsen/camel,mcollovati/camel,christophd/camel,christophd/camel,pmoerenhout/camel,tdiesler/camel,apache/camel,mcollovati/camel,christophd/camel,DariusX/camel,pmoerenhout/camel,cunningt/camel,gnodet/camel,apache/camel,alvinkwekel/camel,tdiesler/camel,pmoerenhout/camel,mcollovati/camel,adessaigne/camel,ullgren/camel,objectiser/camel,pmoerenhout/camel,DariusX/camel,tadayosi/camel,nicolaferraro/camel,pax95/camel,objectiser/camel,CodeSmell/camel,CodeSmell/camel,Fabryprog/camel,nikhilvibhav/camel,christophd/camel,davidkarlsen/camel,mcollovati/camel,gnodet/camel,apache/camel,nicolaferraro/camel,objectiser/camel,Fabryprog/camel,christophd/camel,nicolaferraro/camel,pax95/camel,tadayosi/camel,pax95/camel,christophd/camel,alvinkwekel/camel,nikhilvibhav/camel,Fabryprog/camel,alvinkwekel/camel | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.spark;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.spark.api.java.JavaRDDLike;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
/**
* The spark component can be used to send RDD or DataFrame jobs to Apache Spark cluster.
*/
@UriEndpoint(firstVersion = "2.17.0", scheme = "spark", title = "Apache Spark", syntax = "spark:endpointType",
producerOnly = true, label = "bigdata,iot")
public class SparkEndpoint extends DefaultEndpoint {
// Logger
private static final Logger LOG = getLogger(SparkEndpoint.class);
// Endpoint collaborators
@UriPath @Metadata(required = true)
private EndpointType endpointType;
@UriParam
private JavaRDDLike rdd;
@UriParam
private RddCallback rddCallback;
@UriParam
private Dataset<Row> dataFrame;
@UriParam
private DataFrameCallback dataFrameCallback;
// Endpoint configuration
@UriParam(defaultValue = "true")
private boolean collect = true;
// Constructors
public SparkEndpoint(String endpointUri, SparkComponent component, EndpointType endpointType) {
super(endpointUri, component);
this.endpointType = endpointType;
}
// Life-cycle
@Override
protected void doStart() throws Exception {
super.doStart();
if (rdd == null) {
rdd = getComponent().getRdd();
}
if (rddCallback == null) {
rddCallback = getComponent().getRddCallback();
}
}
// Overridden
@Override
public Producer createProducer() throws Exception {
LOG.trace("Creating {} Spark producer.", endpointType);
if (endpointType == EndpointType.rdd) {
LOG.trace("About to create RDD producer.");
return new RddSparkProducer(this);
} else if (endpointType == EndpointType.dataframe) {
LOG.trace("About to create DataFrame producer.");
return new DataFrameSparkProducer(this);
} else {
LOG.trace("About to create Hive producer.");
return new HiveSparkProducer(this);
}
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("Spark component supports producer endpoints only.");
}
@Override
public boolean isSingleton() {
return true;
}
// Setters & getters
@Override
public SparkComponent getComponent() {
return (SparkComponent) super.getComponent();
}
public EndpointType getEndpointType() {
return endpointType;
}
/**
* Type of the endpoint (rdd, dataframe, hive).
*/
public void setEndpointType(EndpointType endpointType) {
this.endpointType = endpointType;
}
public JavaRDDLike getRdd() {
return rdd;
}
/**
* RDD to compute against.
*/
public void setRdd(JavaRDDLike rdd) {
this.rdd = rdd;
}
public RddCallback getRddCallback() {
return rddCallback;
}
/**
* Function performing action against an RDD.
*/
public void setRddCallback(RddCallback rddCallback) {
this.rddCallback = rddCallback;
}
public Dataset<Row> getDataFrame() {
return dataFrame;
}
/**
* DataFrame to compute against.
*/
public void setDataFrame(Dataset<Row> dataFrame) {
this.dataFrame = dataFrame;
}
public DataFrameCallback getDataFrameCallback() {
return dataFrameCallback;
}
/**
* Function performing action against an DataFrame.
*/
public void setDataFrameCallback(DataFrameCallback dataFrameCallback) {
this.dataFrameCallback = dataFrameCallback;
}
public boolean isCollect() {
return collect;
}
/**
* Indicates if results should be collected or counted.
*/
public void setCollect(boolean collect) {
this.collect = collect;
}
}
| components/camel-spark/src/main/java/org/apache/camel/component/spark/SparkEndpoint.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.spark;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.spark.api.java.JavaRDDLike;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
/**
* The spark component can be used to send RDD or DataFrame jobs to Apache Spark cluster.
*/
@UriEndpoint(firstVersion = "2.17.0", scheme = "spark", title = "Apache Spark", syntax = "spark:endpointType",
producerOnly = true, label = "bigdata,iot")
public class SparkEndpoint extends DefaultEndpoint {
// Logger
private static final Logger LOG = getLogger(SparkEndpoint.class);
// Endpoint collaborators
@UriPath @Metadata(required = true)
private EndpointType endpointType;
@UriParam
private JavaRDDLike rdd;
@UriParam
private RddCallback rddCallback;
@UriParam
private Dataset<Row> dataFrame;
@UriParam
private DataFrameCallback dataFrameCallback;
// Endpoint configuration
@UriParam(defaultValue = "true")
private boolean collect = true;
// Constructors
public SparkEndpoint(String endpointUri, SparkComponent component, EndpointType endpointType) {
super(endpointUri, component);
this.endpointType = endpointType;
}
// Life-cycle
@Override
protected void doStart() throws Exception {
super.doStart();
if (rdd == null) {
rdd = getComponent().getRdd();
}
if (rddCallback == null) {
rddCallback = getComponent().getRddCallback();
}
}
// Overridden
@Override
public Producer createProducer() throws Exception {
LOG.trace("Creating {} Spark producer.", endpointType);
if (endpointType == EndpointType.rdd) {
LOG.trace("About to create RDD producer.");
return new RddSparkProducer(this);
} else if (endpointType == EndpointType.dataframe) {
LOG.trace("About to create DataFrame producer.");
return new DataFrameSparkProducer(this);
} else {
LOG.trace("About to create Hive producer.");
return new HiveSparkProducer(this);
}
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("Spark component supports producer endpoints only.");
}
@Override
public boolean isSingleton() {
return true;
}
// Setters & getters
@Override
public SparkComponent getComponent() {
return (SparkComponent) super.getComponent();
}
public EndpointType getEndpointType() {
return endpointType;
}
/**
* Type of the endpoint (rdd, dataframe, hive).
*/
public void setEndpointType(EndpointType endpointType) {
this.endpointType = endpointType;
}
public JavaRDDLike getRdd() {
return rdd;
}
/**
* RDD to compute against.
*/
public void setRdd(JavaRDDLike rdd) {
this.rdd = rdd;
}
public RddCallback getRddCallback() {
return rddCallback;
}
/**
* Function performing action against an RDD.
*/
public void setRddCallback(RddCallback rddCallback) {
this.rddCallback = rddCallback;
}
public Dataset<Row> getDataFrame() {
return dataFrame;
}
/**
* DataFrame to compute against.
*/
public void setDataFrame(Dataset<Row> dataFrame) {
this.dataFrame = dataFrame;
}
public DataFrameCallback getDataFrameCallback() {
return dataFrameCallback;
}
/**
* Function performing action against an DataFrame.
*/
public void setDataFrameCallback(DataFrameCallback dataFrameCallback) {
this.dataFrameCallback = dataFrameCallback;
}
public boolean isCollect() {
return collect;
}
/**
* Indicates if results should be collected or counted.
*/
public void setCollect(boolean collect) {
this.collect = collect;
}
} | Fixed CS for Camel-Spark
| components/camel-spark/src/main/java/org/apache/camel/component/spark/SparkEndpoint.java | Fixed CS for Camel-Spark | <ide><path>omponents/camel-spark/src/main/java/org/apache/camel/component/spark/SparkEndpoint.java
<ide> import org.apache.camel.Consumer;
<ide> import org.apache.camel.Processor;
<ide> import org.apache.camel.Producer;
<del>import org.apache.camel.support.DefaultEndpoint;
<ide> import org.apache.camel.spi.Metadata;
<ide> import org.apache.camel.spi.UriEndpoint;
<ide> import org.apache.camel.spi.UriParam;
<ide> import org.apache.camel.spi.UriPath;
<add>import org.apache.camel.support.DefaultEndpoint;
<ide> import org.apache.spark.api.java.JavaRDDLike;
<ide> import org.apache.spark.sql.Dataset;
<ide> import org.apache.spark.sql.Row; |
|
Java | mit | abbcb7e927fe51f73d2dea7602d51f80f12c4b6e | 0 | javadev/underscore-java,javadev/underscore-java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Valentyn Kolesnikov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.underscore;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* Underscore library in java.
*
* @author Valentyn Kolesnikov
*/
public final class _<T> {
private final Iterable<T> iterable;
public _(final Iterable<T> iterable) {
this.iterable = iterable;
}
public static <T> void each(final Iterable<T> iterable, final Block<? super T> func) {
for (T element : iterable) {
func.apply(element);
}
}
public static <T> void forEach(final Iterable<T> iterable, final Block<? super T> func) {
each(iterable, func);
}
public static <T, E> List<T> map(final List<E> list, final Function1<? super E, T> func) {
final List<T> transformed = new ArrayList<T>(list.size());
for (E element : list) {
transformed.add(func.apply(element));
}
return transformed;
}
public static <T, E> Set<T> map(final Set<E> set, final Function1<? super E, T> func) {
final Set<T> transformed = new LinkedHashSet<T>(set.size());
for (E element : set) {
transformed.add(func.apply(element));
}
return transformed;
}
public static <T, E> List<T> collect(final List<E> list, final Function1<? super E, T> func) {
return map(list, func);
}
public static <T, E> Set<T> collect(final Set<E> set, final Function1<? super E, T> func) {
return map(set, func);
}
public static <E> E reduce(final Iterable<E> iterable, final E zeroElem, final Function2<E, E, E> func) {
E accum = zeroElem;
for (E element : iterable) {
accum = func.apply(accum, element);
}
return accum;
}
public static <E> E inject(final Iterable<E> iterable, final E zeroElem, final Function2<E, E, E> func) {
return reduce(iterable, zeroElem, func);
}
public static <E> E foldl(final Iterable<E> iterable, final E zeroElem, final Function2<E, E, E> func) {
return reduce(iterable, zeroElem, func);
}
public static <E> E reduceRight(final Iterable<E> iterable, final E zeroElem, final Function2<E, E, E> func) {
final List<E> list = new ArrayList<E>();
for (E elem : iterable) {
list.add(0, elem);
}
E accum = zeroElem;
for (E element : list) {
accum = func.apply(accum, element);
}
return accum;
}
public static <E> E reduceRight(final Iterable<E> iterable, final E zeroElem, final Function1<E, E> func) {
final List<E> list = new ArrayList<E>();
for (E elem : iterable) {
list.add(0, elem);
}
E accum = zeroElem;
int index = 0;
for (E elem : list) {
accum = func.apply(accum);
index += 1;
}
return accum;
}
public static <E> E foldr(final Iterable<E> iterable, final E zeroElem, final Function1<E, E> func) {
return reduceRight(iterable, zeroElem, func);
}
public static <E> E foldr(final Iterable<E> iterable, final E zeroElem, final Function2<E, E, E> func) {
return reduceRight(iterable, zeroElem, func);
}
public static <E> E find(final Iterable<E> iterable, final Predicate<E> pred) {
for (E element : iterable) {
if (pred.apply(element)) {
return element;
}
}
return null;
}
public static <E> E detect(final Iterable<E> iterable, final Predicate<E> pred) {
return find(iterable, pred);
}
public static <E> List<E> filter(final List<E> list,
final Predicate<E> pred) {
final List<E> filtered = new ArrayList<E>();
for (E element : list) {
if (pred.apply(element)) {
filtered.add(element);
}
}
return filtered;
}
public static <E> Set<E> filter(final Set<E> set,
final Predicate<E> pred) {
final Set<E> filtered = new LinkedHashSet<E>();
for (E element : set) {
if (pred.apply(element)) {
filtered.add(element);
}
}
return filtered;
}
public static <E> List<E> select(final List<E> list,
final Predicate<E> pred) {
return filter(list, pred);
}
public static <E> Set<E> select(final Set<E> set,
final Predicate<E> pred) {
return filter(set, pred);
}
public static <E> List<E> where(final List<E> list,
final Iterable<Tuple<String, E>> properties) {
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(final E elem) {
for (Tuple<String, E> prop : properties) {
try {
if (!elem.getClass().getField(prop.fst()).get(elem)
.equals(prop.snd())) {
return false;
}
} catch (Exception ex) {
//throw new IllegalArgumentException(ex);
return false;
}
}
return true;
}
});
}
public static <E> Set<E> where(final Set<E> list,
final Iterable<Tuple<String, E>> properties) {
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(final E elem) {
for (Tuple<String, E> prop : properties) {
try {
if (!elem.getClass().getField(prop.fst()).get(elem)
.equals(prop.snd())) {
return false;
}
} catch (Exception ex) {
//throw new IllegalArgumentException(ex);
return false;
}
}
return true;
}
});
}
public static <E> E findWhere(final Iterable<E> iterable,
final Iterable<Tuple<String, E>> properties) {
return find(iterable, new Predicate<E>() {
@Override
public Boolean apply(final E elem) {
for (Tuple<String, E> prop : properties) {
try {
if (!elem.getClass().getField(prop.fst()).get(elem)
.equals(prop.snd())) {
return false;
}
} catch (Exception ex) {
//throw new IllegalArgumentException(ex);
return false;
}
}
return true;
}
});
}
public static <E> List<E> reject(final List<E> list, final Predicate<E> pred) {
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(E input) {
return !pred.apply(input);
}
});
}
public static <E> Set<E> reject(final Set<E> set, final Predicate<E> pred) {
return filter(set, new Predicate<E>() {
@Override
public Boolean apply(E input) {
return !pred.apply(input);
}
});
}
public static <E> boolean every(final Iterable<E> iterable, final Predicate<E> pred) {
return find(iterable, new Predicate<E>() {
@Override
public Boolean apply(E arg) {
return !pred.apply(arg);
}
}) == null;
}
public static <E> boolean all(final Iterable<E> set, final Predicate<E> pred) {
return every(set, pred);
}
public static <E> boolean some(final Iterable<E> iterable, final Predicate<E> pred) {
return find(iterable, pred) != null;
}
public static <E> boolean any(final Iterable<E> iterable, final Predicate<E> pred) {
return some(iterable, pred);
}
public static <E> boolean contains(final Iterable<E> iterable, final E elem) {
return some(iterable, new Predicate<E>() {
@Override
public Boolean apply(E e) {
return elem.equals(e);
}
});
}
public static <E> boolean include(final Iterable<E> iterable, final E elem) {
return contains(iterable, elem);
}
public static <E> void invoke(final Iterable<E> iterable, final String methodName,
final List<Object> args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
final List<Class<?>> argTypes = map(args, new Function1<Object, Class<?>>() {
public Class<?> apply(Object input) {
return input.getClass();
}
});
final Method method = iterable.getClass().getMethod(methodName, argTypes.toArray(new Class[argTypes.size()]));
_.each(iterable, new Block<E>() {
public void apply(E arg) {
try {
method.invoke(iterable, args.toArray(new Object[args.size()]));
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
});
}
public static <E> void invoke(final Iterable<E> iterable, final String methodName) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
invoke(iterable, methodName, Collections.emptyList());
}
public static <E> List<Object> pluck(final List<E> list,
final String propertyName) throws NoSuchFieldException, SecurityException {
if (list.isEmpty()) {
return Collections.emptyList();
}
final Field field = list.get(0).getClass().getField(propertyName);
return _.map(list, new Function1<E, Object>() {
@Override
public Object apply(E input) {
try {
return field.get(input);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
});
}
public static <E> Set<Object> pluck(final Set<E> set,
final String propertyName) throws NoSuchFieldException, SecurityException {
if (set.isEmpty()) {
return Collections.emptySet();
}
return _.map(set, new Function1<E, Object>() {
@Override
public Object apply(E elem) {
try {
return elem.getClass().getField(propertyName).get(elem);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
});
}
public static <E extends Comparable<? super E>> E max(final Collection<E> collection) {
return Collections.max(collection);
}
public static <E, F extends Comparable> E max(final Collection<E> collection, final Function1<E, F> func) {
return Collections.max(collection, new Comparator<E>() {
@Override
public int compare(E o1, E o2) {
return func.apply(o1).compareTo(func.apply(o2));
}
});
}
public static <E extends Comparable<? super E>> E min(final Collection<E> collection) {
return Collections.min(collection);
}
public static <E, F extends Comparable> E min(final Collection<E> collection, final Function1<E, F> func) {
return Collections.min(collection, new Comparator<E>() {
@Override
public int compare(E o1, E o2) {
return func.apply(o1).compareTo(func.apply(o2));
}
});
}
public static <E, T extends Comparable<? super T>> List<E> sortBy(final List<E> list, final Function1<E, T> func) {
final List<E> sortedList = new ArrayList<E>();
_.each(list, new Block<E>() {
@Override
public void apply(E arg) {
sortedList.add(arg);
}
});
Collections.sort(sortedList, new Comparator<E>() {
@Override
public int compare(E o1, E o2) {
return func.apply(o1).compareTo(func.apply(o2));
}
});
return sortedList;
}
public static <K, E> Map<K, List<E>> groupBy(final Iterable<E> iterable, final Function1<E, K> func) {
final Map<K, List<E>> retVal = new LinkedHashMap<K, List<E>>();
for (E e : iterable) {
final K key = func.apply(e);
List<E> val;
if (retVal.containsKey(key)) {
val = retVal.get(key);
} else {
val = new ArrayList<E>();
}
val.add(e);
retVal.put(key, val);
}
return retVal;
}
public static <K, E> Map<K, List<E>> indexBy(final Iterable<E> iterable, final String property) {
return groupBy(iterable, new Function1<E, K>() {
@Override
public K apply(E elem) {
try {
return (K) elem.getClass().getField(property).get(elem);
} catch (NoSuchFieldException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
});
}
public static <K, E> Map<K, Integer> countBy(final Iterable<E> iterable, Function1<E, K> func) {
final Map<K, Integer> retVal = new LinkedHashMap<K, Integer>();
for (E e : iterable) {
final K key = func.apply(e);
if (retVal.containsKey(key)) {
retVal.put(key, 1 + retVal.get(key));
} else {
retVal.put(key, 1);
}
}
return retVal;
}
public static <E> List<E> shuffle(final List<E> list) {
final List<E> shuffled = new ArrayList<E>(list);
Collections.shuffle(shuffled);
return shuffled;
}
public static <E> E sample(final List<E> list) {
return list.get(new Random().nextInt(list.size()));
}
public static <E> Set<E> sample(final List<E> list, final int howMany) {
final int size = Math.min(howMany, list.size());
final Set<E> samples = new LinkedHashSet<E>(size);
while (samples.size() < size) {
E sample = sample(list);
samples.add(sample);
}
return samples;
}
public static <E> E[] toArray(final Iterable<E> iterable) {
final List<E> list = new ArrayList<E>();
each(iterable, new Block<E>() {
@Override
public void apply(E elem) {
list.add(elem);
}
});
return (E[]) list.toArray();
}
public static int size(final Iterable<?> iterable) {
int size;
final Iterator<?> iterator = iterable.iterator();
for (size = 0; iterator.hasNext(); size += 1) {
iterator.next();
}
return size;
}
public static <E> E first(final Iterable<E> iterable) {
return iterable.iterator().next();
}
public static <E> E first(final E[] array) {
return array[0];
}
public static <E> List<E> first(final List<E> list, final int n) {
return list.subList(0, n);
}
public T first() {
return iterable.iterator().next();
}
public static <E> List<E> initial(final List<E> list) {
return initial(list, 1);
}
public static <E> List<E> initial(final List<E> list, final int n) {
return list.subList(0, list.size() - n);
}
public static <E> E[] initial(final E[] array) {
return initial(array, 1);
}
public static <E> E[] initial(final E[] array, final int n) {
return Arrays.copyOf(array, array.length - n);
}
public static <E> E last(final E[] array) {
return array[array.length - 1];
}
public static <E> E last(final List<E> list) {
return list.get(list.size() - 1);
}
public static <E> List<E> last(final List<E> list, final int n) {
return list.subList(list.size() - n, list.size());
}
public static <E> List<E> rest(final List<E> list) {
return rest(list, 1);
}
public static <E> List<E> rest(final List<E> list, int n) {
return list.subList(n, list.size());
}
public static <E> List<E> tail(final List<E> list) {
return rest(list);
}
public static <E> List<E> tail(final List<E> list, final int n) {
return rest(list, n);
}
public static <E> List<E> drop(final List<E> list) {
return rest(list);
}
public static <E> List<E> drop(final List<E> list, final int n) {
return rest(list, n);
}
public static <E> E[] rest(final E[] array, final int n) {
return (E[]) rest(Arrays.asList(array), n).toArray();
}
public static <E> E[] rest(final E[] array) {
return rest(array, 1);
}
public static <E> E[] tail(final E[] array) {
return rest(array);
}
public static <E> E[] tail(final E[] array, final int n) {
return rest(array, n);
}
public static <E> E[] drop(final E[] array) {
return rest(array);
}
public static <E> E[] drop(final E[] array, final int n) {
return rest(array, n);
}
public static <E> List<E> compact(final List<E> list) {
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(E arg) {
return !String.valueOf(arg).equals("null") && !String.valueOf(arg).equals("0")
&& !String.valueOf(arg).equals("false") && !String.valueOf(arg).equals("");
}
});
}
public static <E> List<E> compact(final List<E> list, final E falsyValue) {
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(E arg) {
return arg.equals(falsyValue);
}
});
}
public static <E> E[] compact(final E[] array, final E falsyValue) {
return (E[]) compact(Arrays.asList(array), falsyValue).toArray();
}
public static <E> List<E> flatten(final List<?> list) {
List<E> flattened = new ArrayList<E>();
flatten(list, flattened);
return flattened;
}
private static <E> void flatten(final List<?> fromTreeList, final List<E> toFlatList) {
for (Object item : fromTreeList) {
if (item instanceof List<?>) {
flatten((List<?>) item, toFlatList);
} else {
toFlatList.add((E) item);
}
}
}
public static <E> List<E> without(final List<E> list, E... values) {
final List<E> valuesList = Arrays.asList(values);
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(E elem) {
return !contains(valuesList, elem);
}
});
}
public static <E> List<E> without(final List<E> list, final E value) {
return without(list, value);
}
public static <E> E[] without(final E[] array, final E... values) {
return (E[]) without(Arrays.asList(array), values).toArray();
}
public static <E> E[] without(final E[] array, final E value) {
return without(array, (E[]) Arrays.asList(value).toArray());
}
public static <E> List<E> union(final List<E> ... lists) {
final Set<E> union = new LinkedHashSet<E>();
for (List<E> list : lists) {
union.addAll(list);
}
return new ArrayList<E>(union);
}
public static <E> E[] union(final E[] array1, final E[] array2) {
return (E[]) union(Arrays.asList(array1), Arrays.asList(array2)).toArray();
}
public static <E> List<E> intersection(final List<E> list1, final List<E> list2) {
return filter(list1, new Predicate<E>() {
@Override
public Boolean apply(E elem) {
return contains(list2, elem);
}
});
}
public static <E> List<E> intersection(final List<E> ... lists) {
final Stack<List<E>> stack = new Stack<List<E>>();
stack.push(lists[0]);
for (int index = 1; index < lists.length; index += 1) {
stack.push(intersection(stack.peek(), lists[index]));
}
return stack.peek();
}
public static <E> E[] intersection(final E[] array1, final E[] array2) {
return (E[]) intersection(Arrays.asList(array1), Arrays.asList(array2)).toArray();
}
public static <E> List<E> difference(final List<E> list1, final List<E> list2) {
return filter(list1, new Predicate<E>() {
@Override
public Boolean apply(E elem) {
return !contains(list2, elem);
}
});
}
public static <E> E[] difference(final E[] array1, final E[] array2) {
return (E[]) difference(Arrays.asList(array1), Arrays.asList(array2)).toArray();
}
public static <E> List<E> uniq(final List<E> list) {
return new ArrayList<E>(new LinkedHashSet<E>(list));
}
public static <E> E[] uniq(final E[] array) {
return (E[]) uniq(Arrays.asList(array)).toArray();
}
public static <T> List<List<T>> zip(final List<T>... lists) {
final List<List<T>> zipped = new ArrayList<List<T>>();
_.each(Arrays.asList(lists), new Block<List<T>>() {
@Override
public void apply(final List<T> list) {
_.each(list, new Block<T>() {
int index = 0;
@Override
public void apply(T elem) {
final List<T> nTuple = index >= zipped.size() ? new ArrayList<T>() : zipped.get(index);
if (index >= zipped.size()) {
zipped.add(nTuple);
}
index += 1;
nTuple.add(elem);
}
});
}
});
return zipped;
}
public static <T> T[][] zip(final T[]... lists) {
return (T[][]) zip(Arrays.asList(lists)).toArray();
}
public static <K, V> List<Tuple<K, V>> object(final List<K> keys, final List<V> values) {
return _.map(keys, new Function1<K, Tuple<K, V>>() {
int index = 0;
@Override
public Tuple<K, V> apply(K key) {
return Tuple.create(key, values.get(index++));
}
});
}
public static <K, V> Tuple<K, V>[] object(final K[] keys, final V[] values) {
return (Tuple<K, V>[]) object(Arrays.asList(keys), Arrays.asList(values)).toArray();
}
public static <E> int indexOf(final List<E> list, final E value) {
return list.indexOf(value);
}
public static <E> int indexOf(final E[] array, final E value) {
return indexOf(Arrays.asList(array), value);
}
public static <E> int lastIndexOf(final List<E> list, final E value) {
return list.lastIndexOf(value);
}
public static <E> int lastIndexOf(final E[] array, final E value) {
return lastIndexOf(Arrays.asList(array), value);
}
public static <E extends Comparable<E>> int sortedIndex(final List<E> list, final E value) {
int index = 0;
for (E elem : list) {
if (elem.compareTo(value) >= 0) {
return index;
}
index += 1;
}
return -1;
}
public static <E extends Comparable<E>> int sortedIndex(final E[] array, final E value) {
return sortedIndex(Arrays.asList(array), value);
}
public static <E extends Comparable<E>> int sortedIndex(final List<E> list, final E value, final String propertyName) throws NoSuchFieldException, IllegalAccessException {
final Field property = value.getClass().getField(propertyName);
final Object valueProperty = property.get(value);
int index = 0;
for (E elem : list) {
if (((Comparable) property.get(elem)).compareTo(valueProperty) >= 0) {
return index;
}
}
return -1;
}
public static <E extends Comparable<E>> int sortedIndex(final E[] array, final E value, final String propertyName) throws NoSuchFieldException, IllegalAccessException {
return sortedIndex(Arrays.asList(array), value);
}
public static int[] range(int stop) {
return range(0, stop, 1);
}
public static int[] range(int start, int stop) {
return range(start, stop, 1);
}
public static int[] range(int start, int stop, int step) {
int[] array = new int[Math.abs(stop - start) / Math.abs(step)];
int index2 = 0;
if (start < stop) {
for (int index = start; index < stop; index += step, index2 += 1) {
array[index2] = index;
}
} else {
for (int index = start; index > stop; index += step, index2 += 1) {
array[index2] = index;
}
}
return array;
}
public static <F1, T> Function<T> partial(final Function1<F1, T> func, final F1 value) {
return new Function<T>() {
@Override
public T apply() {
return func.apply(value);
}
};
}
public static <F2, F1, T> Function1<F1, T> partial(final Function2<F2, F1, T> func, final F2 value) {
return new Function1<F1, T>() {
@Override
public T apply(F1 arg) {
return func.apply(value, arg);
}
};
}
public static <F3, F2, F1, T> Function2<F2, F1, T> partial(final Function3<F3, F2, F1, T> func, final F3 value) {
return new Function2<F2, F1, T>() {
@Override
public T apply(F2 arg1, F1 arg2) {
return func.apply(value, arg1, arg2);
}
};
}
public static <F4, F3, F2, F1, T> Function3<F3, F2, F1, T> partial(final Function4<F4, F3, F2, F1, T> func, final F4 value) {
return new Function3<F3, F2, F1, T>() {
@Override
public T apply(F3 arg1, F2 arg2, F1 arg3) {
return func.apply(value, arg1, arg2, arg3);
}
};
}
public static <T> T partial(final Object function, final Class<T> unused, final Object... args) {
try {
if (args.length == 0) {
throw new IllegalArgumentException("partial method must have at least one argument");
}
Object currentFunc = function;
for (final Object arg : args) {
final Method partialMethod = _.class.getMethod("partial",
new Class[]{currentFunc.getClass().getInterfaces()[0], Object.class});
currentFunc = partialMethod.invoke(null, new Object[]{currentFunc, arg});
}
return (T) currentFunc;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static <T> Chain chain(final List<T> list) {
return new _.Chain<T>(list);
}
public static class Chain<T> {
private final List<T> list;
public Chain(final List<T> list) {
this.list = list;
}
public Chain<T> first() {
return new Chain<T>(Arrays.asList(_.first(list)));
}
public <F> Chain<F> map(final Function1<? super T, F> func) {
return new Chain<F>(_.map(list, func));
}
public <F extends Comparable<? super F>> Chain<T> sortBy(final Function1<T, F> func) {
return new Chain<T>(_.sortBy(list, func));
}
public String value() {
return list.toString();
}
}
public static void main(String[] args) {
final String message = "Underscore-java is a java port of Underscore.js.\n\n"
+ "In addition to porting Underscore's functionality, Underscore-java includes matching unit tests.\n\n"
+ "For docs, license, tests, and downloads, see: http://javadev.github.com/underscore-java";
System.out.println(message);
}
}
| src/main/java/com/github/uderscore/_.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Valentyn Kolesnikov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.underscore;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* Underscore library in java.
*
* @author Valentyn Kolesnikov
*/
public final class _ {
public static <T> void each(final Iterable<T> iterable, final Block<? super T> func) {
for (T element : iterable) {
func.apply(element);
}
}
public static <T> void forEach(final Iterable<T> iterable, final Block<? super T> func) {
each(iterable, func);
}
public static <T, E> List<T> map(final List<E> list, final Function1<? super E, T> func) {
final List<T> transformed = new ArrayList<T>(list.size());
for (E element : list) {
transformed.add(func.apply(element));
}
return transformed;
}
public static <T, E> Set<T> map(final Set<E> set, final Function1<? super E, T> func) {
final Set<T> transformed = new LinkedHashSet<T>(set.size());
for (E element : set) {
transformed.add(func.apply(element));
}
return transformed;
}
public static <T, E> List<T> collect(final List<E> list, final Function1<? super E, T> func) {
return map(list, func);
}
public static <T, E> Set<T> collect(final Set<E> set, final Function1<? super E, T> func) {
return map(set, func);
}
public static <E> E reduce(final Iterable<E> iterable, final E zeroElem, final Function2<E, E, E> func) {
E accum = zeroElem;
for (E element : iterable) {
accum = func.apply(accum, element);
}
return accum;
}
public static <E> E inject(final Iterable<E> iterable, final E zeroElem, final Function2<E, E, E> func) {
return reduce(iterable, zeroElem, func);
}
public static <E> E foldl(final Iterable<E> iterable, final E zeroElem, final Function2<E, E, E> func) {
return reduce(iterable, zeroElem, func);
}
public static <E> E reduceRight(final Iterable<E> iterable, final E zeroElem, final Function2<E, E, E> func) {
final List<E> list = new ArrayList<E>();
for (E elem : iterable) {
list.add(0, elem);
}
E accum = zeroElem;
for (E element : list) {
accum = func.apply(accum, element);
}
return accum;
}
public static <E> E reduceRight(final Iterable<E> iterable, final E zeroElem, final Function1<E, E> func) {
final List<E> list = new ArrayList<E>();
for (E elem : iterable) {
list.add(0, elem);
}
E accum = zeroElem;
int index = 0;
for (E elem : list) {
accum = func.apply(accum);
index += 1;
}
return accum;
}
public static <E> E foldr(final Iterable<E> iterable, final E zeroElem, final Function1<E, E> func) {
return reduceRight(iterable, zeroElem, func);
}
public static <E> E foldr(final Iterable<E> iterable, final E zeroElem, final Function2<E, E, E> func) {
return reduceRight(iterable, zeroElem, func);
}
public static <E> E find(final Iterable<E> iterable, final Predicate<E> pred) {
for (E element : iterable) {
if (pred.apply(element)) {
return element;
}
}
return null;
}
public static <E> E detect(final Iterable<E> iterable, final Predicate<E> pred) {
return find(iterable, pred);
}
public static <E> List<E> filter(final List<E> list,
final Predicate<E> pred) {
final List<E> filtered = new ArrayList<E>();
for (E element : list) {
if (pred.apply(element)) {
filtered.add(element);
}
}
return filtered;
}
public static <E> Set<E> filter(final Set<E> set,
final Predicate<E> pred) {
final Set<E> filtered = new LinkedHashSet<E>();
for (E element : set) {
if (pred.apply(element)) {
filtered.add(element);
}
}
return filtered;
}
public static <E> List<E> select(final List<E> list,
final Predicate<E> pred) {
return filter(list, pred);
}
public static <E> Set<E> select(final Set<E> set,
final Predicate<E> pred) {
return filter(set, pred);
}
public static <E> List<E> where(final List<E> list,
final Iterable<Tuple<String, E>> properties) {
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(final E elem) {
for (Tuple<String, E> prop : properties) {
try {
if (!elem.getClass().getField(prop.fst()).get(elem)
.equals(prop.snd())) {
return false;
}
} catch (Exception ex) {
//throw new IllegalArgumentException(ex);
return false;
}
}
return true;
}
});
}
public static <E> Set<E> where(final Set<E> list,
final Iterable<Tuple<String, E>> properties) {
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(final E elem) {
for (Tuple<String, E> prop : properties) {
try {
if (!elem.getClass().getField(prop.fst()).get(elem)
.equals(prop.snd())) {
return false;
}
} catch (Exception ex) {
//throw new IllegalArgumentException(ex);
return false;
}
}
return true;
}
});
}
public static <E> E findWhere(final Iterable<E> iterable,
final Iterable<Tuple<String, E>> properties) {
return find(iterable, new Predicate<E>() {
@Override
public Boolean apply(final E elem) {
for (Tuple<String, E> prop : properties) {
try {
if (!elem.getClass().getField(prop.fst()).get(elem)
.equals(prop.snd())) {
return false;
}
} catch (Exception ex) {
//throw new IllegalArgumentException(ex);
return false;
}
}
return true;
}
});
}
public static <E> List<E> reject(final List<E> list, final Predicate<E> pred) {
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(E input) {
return !pred.apply(input);
}
});
}
public static <E> Set<E> reject(final Set<E> set, final Predicate<E> pred) {
return filter(set, new Predicate<E>() {
@Override
public Boolean apply(E input) {
return !pred.apply(input);
}
});
}
public static <E> boolean every(final Iterable<E> iterable, final Predicate<E> pred) {
return find(iterable, new Predicate<E>() {
@Override
public Boolean apply(E arg) {
return !pred.apply(arg);
}
}) == null;
}
public static <E> boolean all(final Iterable<E> set, final Predicate<E> pred) {
return every(set, pred);
}
public static <E> boolean some(final Iterable<E> iterable, final Predicate<E> pred) {
return find(iterable, pred) != null;
}
public static <E> boolean any(final Iterable<E> iterable, final Predicate<E> pred) {
return some(iterable, pred);
}
public static <E> boolean contains(final Iterable<E> iterable, final E elem) {
return some(iterable, new Predicate<E>() {
@Override
public Boolean apply(E e) {
return elem.equals(e);
}
});
}
public static <E> boolean include(final Iterable<E> iterable, final E elem) {
return contains(iterable, elem);
}
public static <E> void invoke(final Iterable<E> iterable, final String methodName,
final List<Object> args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
final List<Class<?>> argTypes = map(args, new Function1<Object, Class<?>>() {
public Class<?> apply(Object input) {
return input.getClass();
}
});
final Method method = iterable.getClass().getMethod(methodName, argTypes.toArray(new Class[argTypes.size()]));
_.each(iterable, new Block<E>() {
public void apply(E arg) {
try {
method.invoke(iterable, args.toArray(new Object[args.size()]));
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
});
}
public static <E> void invoke(final Iterable<E> iterable, final String methodName) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
invoke(iterable, methodName, Collections.emptyList());
}
public static <E> List<Object> pluck(final List<E> list,
final String propertyName) throws NoSuchFieldException, SecurityException {
if (list.isEmpty()) {
return Collections.emptyList();
}
final Field field = list.get(0).getClass().getField(propertyName);
return _.map(list, new Function1<E, Object>() {
@Override
public Object apply(E input) {
try {
return field.get(input);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
});
}
public static <E> Set<Object> pluck(final Set<E> set,
final String propertyName) throws NoSuchFieldException, SecurityException {
if (set.isEmpty()) {
return Collections.emptySet();
}
return _.map(set, new Function1<E, Object>() {
@Override
public Object apply(E elem) {
try {
return elem.getClass().getField(propertyName).get(elem);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
});
}
public static <E extends Comparable<? super E>> E max(final Collection<E> collection) {
return Collections.max(collection);
}
public static <E, F extends Comparable> E max(final Collection<E> collection, final Function1<E, F> func) {
return Collections.max(collection, new Comparator<E>() {
@Override
public int compare(E o1, E o2) {
return func.apply(o1).compareTo(func.apply(o2));
}
});
}
public static <E extends Comparable<? super E>> E min(final Collection<E> collection) {
return Collections.min(collection);
}
public static <E, F extends Comparable> E min(final Collection<E> collection, final Function1<E, F> func) {
return Collections.min(collection, new Comparator<E>() {
@Override
public int compare(E o1, E o2) {
return func.apply(o1).compareTo(func.apply(o2));
}
});
}
public static <E, T extends Comparable<? super T>> List<E> sortBy(final List<E> list, final Function1<E, T> func) {
final List<E> sortedList = new ArrayList<E>();
_.each(list, new Block<E>() {
@Override
public void apply(E arg) {
sortedList.add(arg);
}
});
Collections.sort(sortedList, new Comparator<E>() {
@Override
public int compare(E o1, E o2) {
return func.apply(o1).compareTo(func.apply(o2));
}
});
return sortedList;
}
public static <K, E> Map<K, List<E>> groupBy(final Iterable<E> iterable, final Function1<E, K> func) {
final Map<K, List<E>> retVal = new LinkedHashMap<K, List<E>>();
for (E e : iterable) {
final K key = func.apply(e);
List<E> val;
if (retVal.containsKey(key)) {
val = retVal.get(key);
} else {
val = new ArrayList<E>();
}
val.add(e);
retVal.put(key, val);
}
return retVal;
}
public static <K, E> Map<K, List<E>> indexBy(final Iterable<E> iterable, final String property) {
return groupBy(iterable, new Function1<E, K>() {
@Override
public K apply(E elem) {
try {
return (K) elem.getClass().getField(property).get(elem);
} catch (NoSuchFieldException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
});
}
public static <K, E> Map<K, Integer> countBy(final Iterable<E> iterable, Function1<E, K> func) {
final Map<K, Integer> retVal = new LinkedHashMap<K, Integer>();
for (E e : iterable) {
final K key = func.apply(e);
if (retVal.containsKey(key)) {
retVal.put(key, 1 + retVal.get(key));
} else {
retVal.put(key, 1);
}
}
return retVal;
}
public static <E> List<E> shuffle(final List<E> list) {
final List<E> shuffled = new ArrayList<E>(list);
Collections.shuffle(shuffled);
return shuffled;
}
public static <E> E sample(final List<E> list) {
return list.get(new Random().nextInt(list.size()));
}
public static <E> Set<E> sample(final List<E> list, final int howMany) {
final int size = Math.min(howMany, list.size());
final Set<E> samples = new LinkedHashSet<E>(size);
while (samples.size() < size) {
E sample = sample(list);
samples.add(sample);
}
return samples;
}
public static <E> E[] toArray(final Iterable<E> iterable) {
final List<E> list = new ArrayList<E>();
each(iterable, new Block<E>() {
@Override
public void apply(E elem) {
list.add(elem);
}
});
return (E[]) list.toArray();
}
public static int size(final Iterable<?> iterable) {
int size;
final Iterator<?> iterator = iterable.iterator();
for (size = 0; iterator.hasNext(); size += 1) {
iterator.next();
}
return size;
}
public static <E> E first(final Iterable<E> iterable) {
return iterable.iterator().next();
}
public static <E> E first(final E[] array) {
return array[0];
}
public static <E> List<E> initial(final List<E> list) {
return initial(list, 1);
}
public static <E> List<E> initial(final List<E> list, final int n) {
return list.subList(0, list.size() - n);
}
public static <E> E[] initial(final E[] array) {
return initial(array, 1);
}
public static <E> E[] initial(final E[] array, final int n) {
return Arrays.copyOf(array, array.length - n);
}
public static <E> E last(final E[] array) {
return array[array.length - 1];
}
public static <E> E last(final List<E> list) {
return list.get(list.size() - 1);
}
public static <E> List<E> last(final List<E> list, final int n) {
return list.subList(list.size() - n, list.size());
}
public static <E> List<E> rest(final List<E> list) {
return rest(list, 1);
}
public static <E> List<E> rest(final List<E> list, int n) {
return list.subList(n, list.size());
}
public static <E> List<E> tail(final List<E> list) {
return rest(list);
}
public static <E> List<E> tail(final List<E> list, final int n) {
return rest(list, n);
}
public static <E> List<E> drop(final List<E> list) {
return rest(list);
}
public static <E> List<E> drop(final List<E> list, final int n) {
return rest(list, n);
}
public static <E> E[] rest(final E[] array, final int n) {
return (E[]) rest(Arrays.asList(array), n).toArray();
}
public static <E> E[] rest(final E[] array) {
return rest(array, 1);
}
public static <E> E[] tail(final E[] array) {
return rest(array);
}
public static <E> E[] tail(final E[] array, final int n) {
return rest(array, n);
}
public static <E> E[] drop(final E[] array) {
return rest(array);
}
public static <E> E[] drop(final E[] array, final int n) {
return rest(array, n);
}
public static <E> List<E> compact(final List<E> list) {
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(E arg) {
return !String.valueOf(arg).equals("null") && !String.valueOf(arg).equals("0")
&& !String.valueOf(arg).equals("false") && !String.valueOf(arg).equals("");
}
});
}
public static <E> List<E> compact(final List<E> list, final E falsyValue) {
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(E arg) {
return arg.equals(falsyValue);
}
});
}
public static <E> E[] compact(final E[] array, final E falsyValue) {
return (E[]) compact(Arrays.asList(array), falsyValue).toArray();
}
public static <E> List<E> flatten(final List<?> list) {
List<E> flattened = new ArrayList<E>();
flatten(list, flattened);
return flattened;
}
private static <E> void flatten(final List<?> fromTreeList, final List<E> toFlatList) {
for (Object item : fromTreeList) {
if (item instanceof List<?>) {
flatten((List<?>) item, toFlatList);
} else {
toFlatList.add((E) item);
}
}
}
public static <E> List<E> without(final List<E> list, E... values) {
final List<E> valuesList = Arrays.asList(values);
return filter(list, new Predicate<E>() {
@Override
public Boolean apply(E elem) {
return !contains(valuesList, elem);
}
});
}
public static <E> List<E> without(final List<E> list, final E value) {
return without(list, value);
}
public static <E> E[] without(final E[] array, final E... values) {
return (E[]) without(Arrays.asList(array), values).toArray();
}
public static <E> E[] without(final E[] array, final E value) {
return without(array, (E[]) Arrays.asList(value).toArray());
}
public static <E> List<E> union(final List<E> ... lists) {
final Set<E> union = new LinkedHashSet<E>();
for (List<E> list : lists) {
union.addAll(list);
}
return new ArrayList<E>(union);
}
public static <E> E[] union(final E[] array1, final E[] array2) {
return (E[]) union(Arrays.asList(array1), Arrays.asList(array2)).toArray();
}
public static <E> List<E> intersection(final List<E> list1, final List<E> list2) {
return filter(list1, new Predicate<E>() {
@Override
public Boolean apply(E elem) {
return contains(list2, elem);
}
});
}
public static <E> List<E> intersection(final List<E> ... lists) {
final Stack<List<E>> stack = new Stack<List<E>>();
stack.push(lists[0]);
for (int index = 1; index < lists.length; index += 1) {
stack.push(intersection(stack.peek(), lists[index]));
}
return stack.peek();
}
public static <E> E[] intersection(final E[] array1, final E[] array2) {
return (E[]) intersection(Arrays.asList(array1), Arrays.asList(array2)).toArray();
}
public static <E> List<E> difference(final List<E> list1, final List<E> list2) {
return filter(list1, new Predicate<E>() {
@Override
public Boolean apply(E elem) {
return !contains(list2, elem);
}
});
}
public static <E> E[] difference(final E[] array1, final E[] array2) {
return (E[]) difference(Arrays.asList(array1), Arrays.asList(array2)).toArray();
}
public static <E> List<E> uniq(final List<E> list) {
return new ArrayList<E>(new LinkedHashSet<E>(list));
}
public static <E> E[] uniq(final E[] array) {
return (E[]) uniq(Arrays.asList(array)).toArray();
}
public static <T> List<List<T>> zip(final List<T>... lists) {
final List<List<T>> zipped = new ArrayList<List<T>>();
_.each(Arrays.asList(lists), new Block<List<T>>() {
@Override
public void apply(final List<T> list) {
_.each(list, new Block<T>() {
int index = 0;
@Override
public void apply(T elem) {
final List<T> nTuple = index >= zipped.size() ? new ArrayList<T>() : zipped.get(index);
if (index >= zipped.size()) {
zipped.add(nTuple);
}
index += 1;
nTuple.add(elem);
}
});
}
});
return zipped;
}
public static <T> T[][] zip(final T[]... lists) {
return (T[][]) zip(Arrays.asList(lists)).toArray();
}
public static <K, V> List<Tuple<K, V>> object(final List<K> keys, final List<V> values) {
return _.map(keys, new Function1<K, Tuple<K, V>>() {
int index = 0;
@Override
public Tuple<K, V> apply(K key) {
return Tuple.create(key, values.get(index++));
}
});
}
public static <K, V> Tuple<K, V>[] object(final K[] keys, final V[] values) {
return (Tuple<K, V>[]) object(Arrays.asList(keys), Arrays.asList(values)).toArray();
}
public static <E> int indexOf(final List<E> list, final E value) {
return list.indexOf(value);
}
public static <E> int indexOf(final E[] array, final E value) {
return indexOf(Arrays.asList(array), value);
}
public static <E> int lastIndexOf(final List<E> list, final E value) {
return list.lastIndexOf(value);
}
public static <E> int lastIndexOf(final E[] array, final E value) {
return lastIndexOf(Arrays.asList(array), value);
}
public static <E extends Comparable<E>> int sortedIndex(final List<E> list, final E value) {
int index = 0;
for (E elem : list) {
if (elem.compareTo(value) >= 0) {
return index;
}
index += 1;
}
return -1;
}
public static <E extends Comparable<E>> int sortedIndex(final E[] array, final E value) {
return sortedIndex(Arrays.asList(array), value);
}
public static <E extends Comparable<E>> int sortedIndex(final List<E> list, final E value, final String propertyName) throws NoSuchFieldException, IllegalAccessException {
final Field property = value.getClass().getField(propertyName);
final Object valueProperty = property.get(value);
int index = 0;
for (E elem : list) {
if (((Comparable) property.get(elem)).compareTo(valueProperty) >= 0) {
return index;
}
}
return -1;
}
public static <E extends Comparable<E>> int sortedIndex(final E[] array, final E value, final String propertyName) throws NoSuchFieldException, IllegalAccessException {
return sortedIndex(Arrays.asList(array), value);
}
public static int[] range(int stop) {
return range(0, stop, 1);
}
public static int[] range(int start, int stop) {
return range(start, stop, 1);
}
public static int[] range(int start, int stop, int step) {
int[] array = new int[Math.abs(stop - start) / Math.abs(step)];
int index2 = 0;
if (start < stop) {
for (int index = start; index < stop; index += step, index2 += 1) {
array[index2] = index;
}
} else {
for (int index = start; index > stop; index += step, index2 += 1) {
array[index2] = index;
}
}
return array;
}
public static <F1, T> Function<T> partial(final Function1<F1, T> func, final F1 value) {
return new Function<T>() {
@Override
public T apply() {
return func.apply(value);
}
};
}
public static <F2, F1, T> Function1<F1, T> partial(final Function2<F2, F1, T> func, final F2 value) {
return new Function1<F1, T>() {
@Override
public T apply(F1 arg) {
return func.apply(value, arg);
}
};
}
public static <F3, F2, F1, T> Function2<F2, F1, T> partial(final Function3<F3, F2, F1, T> func, final F3 value) {
return new Function2<F2, F1, T>() {
@Override
public T apply(F2 arg1, F1 arg2) {
return func.apply(value, arg1, arg2);
}
};
}
public static <F4, F3, F2, F1, T> Function3<F3, F2, F1, T> partial(final Function4<F4, F3, F2, F1, T> func, final F4 value) {
return new Function3<F3, F2, F1, T>() {
@Override
public T apply(F3 arg1, F2 arg2, F1 arg3) {
return func.apply(value, arg1, arg2, arg3);
}
};
}
public static <T> T partial(final Object function, final Class<T> unused, final Object... args) {
try {
if (args.length == 0) {
throw new IllegalArgumentException("partial method must have at least one argument");
}
Object currentFunc = function;
for (final Object arg : args) {
final Method partialMethod = _.class.getMethod("partial",
new Class[]{currentFunc.getClass().getInterfaces()[0], Object.class});
currentFunc = partialMethod.invoke(null, new Object[]{currentFunc, arg});
}
return (T) currentFunc;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static <T> Chain chain(final List<T> list) {
return new _.Chain<T>(list);
}
public static class Chain<T> {
private final List<T> list;
public Chain(final List<T> list) {
this.list = list;
}
public Chain<T> first() {
return new Chain<T>(Arrays.asList(_.first(list)));
}
public <F> Chain<F> map(final Function1<? super T, F> func) {
return new Chain<F>(_.map(list, func));
}
public <F extends Comparable<? super F>> Chain<T> sortBy(final Function1<T, F> func) {
return new Chain<T>(_.sortBy(list, func));
}
public String value() {
return list.toString();
}
}
public static void main(String[] args) {
final String message = "Underscore-java is a java port of Underscore.js.\n\n"
+ "In addition to porting Underscore's functionality, Underscore-java includes matching unit tests.\n\n"
+ "For docs, license, tests, and downloads, see: http://javadev.github.com/underscore-java";
System.out.println(message);
}
}
| Added more junit tests
| src/main/java/com/github/uderscore/_.java | Added more junit tests | <ide><path>rc/main/java/com/github/uderscore/_.java
<ide> *
<ide> * @author Valentyn Kolesnikov
<ide> */
<del>public final class _ {
<add>public final class _<T> {
<add> private final Iterable<T> iterable;
<add>
<add> public _(final Iterable<T> iterable) {
<add> this.iterable = iterable;
<add> }
<add>
<ide> public static <T> void each(final Iterable<T> iterable, final Block<? super T> func) {
<ide> for (T element : iterable) {
<ide> func.apply(element);
<ide> return array[0];
<ide> }
<ide>
<add> public static <E> List<E> first(final List<E> list, final int n) {
<add> return list.subList(0, n);
<add> }
<add>
<add> public T first() {
<add> return iterable.iterator().next();
<add> }
<add>
<ide> public static <E> List<E> initial(final List<E> list) {
<ide> return initial(list, 1);
<ide> } |
|
JavaScript | apache-2.0 | a2058912d404c7c1e3570a281dbb0e70ffd40a7b | 0 | webfirmframework/wff,webfirmframework/wff | /**
*
*/
var wffClientCRUDUtil = new function() {
var encoder = wffGlobal.encoder;
var decoder = wffGlobal.decoder;
var getStringFromBytes = function(utf8Bytes) {
return decoder.decode(new Uint8Array(utf8Bytes));
};
var invokeTask = function(nameValues) {
var taskNameValue = nameValues[0];
// var taskName = getStringFromBytes(taskNameValue.name);
var taskValue = taskNameValue.values[0][0];
console.log('taskNameValue.name', taskNameValue.name);
if (taskValue == wffGlobal.taskValues.ATTRIBUTE_UPDATED) {
console.log('taskValue == "ATTRIBUTE_UPDATED"');
for (var i = 1; i < nameValues.length; i++) {
console.log('i', i);
console.log('nameValues[i].values', nameValues[i].values);
var attrNameValue = getStringFromBytes(nameValues[i].name);
console.log('attrNameValue', attrNameValue);
var indexOfSeparator = attrNameValue.indexOf('=');
var attrNameValueArry = wffTagUtil
.splitAttrNameValue(attrNameValue);
var attrName = attrNameValueArry[0];
var attrValue = attrNameValueArry[1];
// if (indexOfSeparator != -1) {
// attrName = attrNameValue.substring(0, indexOfSeparator);
// attrValue = attrNameValue.substring(indexOfSeparator + 1,
// attrNameValue.length);
// } else {
// attrName = attrNameValue;
// attrValue = '';
// }
console.log('attrName', attrName, 'attrValue', attrValue);
// var tagId = wffBMUtil
// .getIntFromOptimizedBytes(nameValues[i].name);
var wffIds = nameValues[i].values;
// var tagName = getStringFromBytes(wffIds[0]);
for (var j = 0; j < wffIds.length; j++) {
console.log('j', j);
var wffId = wffTagUtil.getWffIdFromWffIdBytes(wffIds[j]);
var applicableTag = wffTagUtil.getTagByWffId(wffId);
if (indexOfSeparator != -1) {
//value attribute doesn't work with setAttribute method
//should be called before setAttribute method
applicableTag[attrName] = attrValue;
applicableTag.setAttribute(attrName, attrValue);
} else {
//value attribute doesn't work with setAttribute method
//should be called before setAttribute method
applicableTag[attrName] = "";
applicableTag.setAttribute(attrName, "");
}
}
}
} else if (taskValue == wffGlobal.taskValues.REMOVED_ATTRIBUTE) {
console.log('taskValue == "REMOVED_ATTRIBUTE"');
for (var i = 1; i < nameValues.length; i++) {
console.log('i', i);
console.log('nameValues[i].values', nameValues[i].values);
var attrName = getStringFromBytes(nameValues[i].name);
console.log('attrName', attrName);
// var tagId = wffBMUtil
// .getIntFromOptimizedBytes(nameValues[i].name);
var wffIds = nameValues[i].values;
// var tagName = getStringFromBytes(wffIds[0]);
for (var j = 0; j < wffIds.length; j++) {
console.log('j', j);
var wffId = wffTagUtil.getWffIdFromWffIdBytes(wffIds[j]);
var applicableTag = wffTagUtil.getTagByWffId(wffId);
applicableTag.removeAttribute(attrName);
}
}
} else if (taskValue == wffGlobal.taskValues.APPENDED_CHILD_TAG
|| taskValue == wffGlobal.taskValues.APPENDED_CHILDREN_TAGS) {
for (var i = 1; i < nameValues.length; i++) {
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[i].name);
var values = nameValues[i].values;
var tagName = getStringFromBytes(values[0]);
var parent = wffTagUtil.getTagByTagNameAndWffId(tagName, wffId);
for (var j = 1; j < values.length; j++) {
// var htmlString = getStringFromBytes(values[j]);
// var div = document.createElement('div');
// div.innerHTML = htmlString;
// var htmlNodes = div.firstChild;
if (parent == undefined) {
console.log('parent == undefined', 'tagName', tagName,
'wffId', wffId);
}
var htmlNodes = wffTagUtil
.createTagFromWffBMBytes(values[j]);
parent.appendChild(htmlNodes);
}
}
} else if (taskValue == wffGlobal.taskValues.REMOVED_TAGS) {
console.log('wffGlobal.taskValues.REMOVED_TAGS nameValues.length '
+ nameValues.length);
for (var i = 1; i < nameValues.length; i++) {
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[i].name);
var values = nameValues[i].values;
var tagName = getStringFromBytes(values[0]);
var tagToRemove = wffTagUtil.getTagByTagNameAndWffId(tagName,
wffId);
console.log('tagToRemove', tagToRemove, 'tagName', tagName,
'wffId', wffId, 'count i', i);
var parent = tagToRemove.parentNode;
parent.removeChild(tagToRemove);
}
} else if (taskValue == wffGlobal.taskValues.REMOVED_ALL_CHILDREN_TAGS) {
console.log('wffGlobal.taskValues.REMOVED_ALL_CHILDREN_TAGS');
for (var i = 1; i < nameValues.length; i++) {
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[i].name);
var values = nameValues[i].values;
var tagName = getStringFromBytes(values[0]);
var parentTag = wffTagUtil.getTagByTagNameAndWffId(tagName,
wffId);
while (parentTag.firstChild) {
parentTag.removeChild(parentTag.firstChild);
}
}
} else if (taskValue == wffGlobal.taskValues.MOVED_CHILDREN_TAGS) {
console
.log('wffGlobal.taskValues.MOVED_CHILDREN_TAGS nameValues.length '
+ nameValues.length);
for (var i = 1; i < nameValues.length; i++) {
var currentParentWffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[i].name);
var values = nameValues[i].values;
var currentParentTagName = getStringFromBytes(values[0]);
var currentParentTag = wffTagUtil.getTagByTagNameAndWffId(
currentParentTagName, currentParentWffId);
var childWffId = wffTagUtil.getWffIdFromWffIdBytes(values[1]);
var childTagName = getStringFromBytes(values[2]);
var childTag = wffTagUtil.getTagByTagNameAndWffId(childTagName,
childWffId);
if (childTag !== undefined) {
var previousParent = childTag.parentNode;
console.log('childTag !== undefined', childTag);
previousParent.removeChild(childTag);
} else {
console.log('childTag === undefined', childTag);
childTag = wffTagUtil.createTagFromWffBMBytes(values[3]);
}
currentParentTag.appendChild(childTag);
}
} else if (taskValue == wffGlobal.taskValues.ADDED_ATTRIBUTES) {
console.log('taskValue == "ADDED_ATTRIBUTES"');
for (var i = 1; i < nameValues.length; i++) {
var nameValue = nameValues[i];
if (nameValue.name[0] == wffGlobal.taskValues.MANY_TO_ONE) {
var tagName = getStringFromBytes(nameValue.values[0]);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValue.values[1]);
var applicableTag = wffTagUtil.getTagByTagNameAndWffId(
tagName, wffId);
for (var j = 2; j < nameValue.values.length; j++) {
var attrNameValue = getStringFromBytes(nameValue.values[j]);
var attrNameValueArry = wffTagUtil
.splitAttrNameValue(attrNameValue);
var attrName = attrNameValueArry[0];
var attrValue = attrNameValueArry[1];
//value attribute doesn't work with setAttribute method
//should be called before setAttribute method
applicableTag[attrName] = attrValue;
applicableTag.setAttribute(attrName, attrValue);
}
}
}
} else if (taskValue == wffGlobal.taskValues.REMOVED_ATTRIBUTES) {
console.log('taskValue == "REMOVED_ATTRIBUTES"');
for (var i = 1; i < nameValues.length; i++) {
var nameValue = nameValues[i];
if (nameValue.name[0] == wffGlobal.taskValues.MANY_TO_ONE) {
var tagName = getStringFromBytes(nameValue.values[0]);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValue.values[1]);
var applicableTag = wffTagUtil.getTagByTagNameAndWffId(
tagName, wffId);
for (var j = 2; j < nameValue.values.length; j++) {
var attrName = getStringFromBytes(nameValue.values[j]);
applicableTag.removeAttribute(attrName);
}
}
}
} else if (taskValue == wffGlobal.taskValues.ADDED_INNER_HTML) {
console.log('wffGlobal.taskValues.ADDED_INNER_HTML');
var tagName = getStringFromBytes(nameValues[1].name);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[1].values[0]);
var parentTag = wffTagUtil.getTagByTagNameAndWffId(tagName,
wffId);
// it should be case sensitive node.innerHTML
// parentTag.innerHTML = innerHtml;
// inner html will not work with table
while (parentTag.firstChild) {
parentTag.removeChild(parentTag.firstChild);
}
for (var i = 2; i < nameValues.length; i++) {
var values = nameValues[i].values;
var htmlNodes = wffTagUtil.createTagFromWffBMBytes(nameValues[i].name);
//if length is 1 then there is an existing tag with this id
if (values.length == 1 && values[0].length == 1) {
console.log('values.length == 3');
var existingTag = wffTagUtil.getTagByTagNameAndWffId(
htmlNodes.nodeName, htmlNodes
.getAttribute("data-wff-id"));
if (existingTag) {
var parentOfExistingTag = existingTag.parentNode;
parentOfExistingTag.removeChild(existingTag);
}
}
parentTag.appendChild(htmlNodes);
}
} else if (taskValue == wffGlobal.taskValues.INSERTED_BEFORE_TAG) {
console.log('wffGlobal.taskValues.INSERTED_BEFORE_TAG');
for (var i = 1; i < nameValues.length; i++) {
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[i].name);
var values = nameValues[i].values;
var tagName = getStringFromBytes(values[0]);
// var innerHtml = getStringFromBytes(values[1]);
// console.log('innerHtml', innerHtml);
var parentTag = wffTagUtil.getTagByTagNameAndWffId(tagName,
wffId);
var beforeTagName = getStringFromBytes(values[2]);
var beforeTagWffId = wffTagUtil.getWffIdFromWffIdBytes(values[3]);
var beforeTag = wffTagUtil.getTagByTagNameAndWffId(beforeTagName,
beforeTagWffId);
var htmlNodes = wffTagUtil.createTagFromWffBMBytes(values[1]);
//if length is 3 then there is an existing tag with this id
if (values.length == 5) {
console.log('values.length == 5');
var existingTag = wffTagUtil.getTagByTagNameAndWffId(
htmlNodes.nodeName, htmlNodes
.getAttribute("data-wff-id"));
var parentOfExistingTag = existingTag.parentNode;
parentOfExistingTag.removeChild(existingTag);
}
parentTag.insertBefore(htmlNodes, beforeTag);
}
} else if (taskValue == wffGlobal.taskValues.RELOAD_BROWSER) {
location.reload(true);
} else if (taskValue == wffGlobal.taskValues.RELOAD_BROWSER_FROM_CACHE) {
location.reload();
} else if (taskValue == wffGlobal.taskValues.EXECURE_JS) {
var js = getStringFromBytes(taskNameValue.values[1]);
if (window.execScript) {
window.execScript(js);
} else {
eval(js);
}
} else if (taskValue == wffGlobal.taskValues.COPY_INNER_TEXT_TO_VALUE) {
console.log('wffGlobal.taskValues.COPY_INNER_TEXT_TO_VALUE');
var tagName = getStringFromBytes(nameValues[1].name);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[1].values[0]);
var parentTag = wffTagUtil.getTagByTagNameAndWffId(tagName,
wffId);
var d = document.createElement('div');
d.innerHTML = parentTag.outerHTML;
parentTag.value = d.childNodes[0].innerText;
} else if (taskValue == wffGlobal.taskValues.SET_BM_OBJ_ON_TAG
|| taskValue == wffGlobal.taskValues.SET_BM_ARR_ON_TAG) {
var tagName = getStringFromBytes(nameValues[1].name);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[1].values[0]);
var tag = wffTagUtil.getTagByTagNameAndWffId(tagName, wffId);
var ky = getStringFromBytes(nameValues[1].values[1]);
var bmObjOrArrBytes = nameValues[1].values[2];
var jsObjOrArr;
if (taskValue == wffGlobal.taskValues.SET_BM_OBJ_ON_TAG) {
jsObjOrArr = new JsObjectFromBMBytes(bmObjOrArrBytes, true);
} else {
jsObjOrArr = new JsArrayFromBMBytes(bmObjOrArrBytes, true);
}
var wffObjects = tag['wffObjects'];
if(typeof wffObjects === 'undefined') {
wffObjects = {};
tag['wffObjects'] = wffObjects;
}
wffObjects[ky] = jsObjOrArr;
} else if (taskValue == wffGlobal.taskValues.DEL_BM_OBJ_OR_ARR_FROM_TAG) {
var tagName = getStringFromBytes(nameValues[1].name);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[1].values[0]);
var tag = wffTagUtil.getTagByTagNameAndWffId(tagName, wffId);
var ky = getStringFromBytes(nameValues[1].values[1]);
var wffObjects = tag['wffObjects'];
if(typeof wffObjects !== 'undefined') {
delete wffObjects[ky];
}
}
return true;
// else if (taskValue == 'DA') {
//
// for (var i = 1; i < nameValues.length; i++) {
//
// var tagId = wffBMUtil
// .getIntFromOptimizedBytes(nameValues[i].name);
// var attrNames = nameValues[i].values;
//
// var tagName = getStringFromBytes(attrNames[0]);
//
// for (var j = 1; j < attrNames.length; j++) {
//
// var attrName = getStringFromBytes(attrNames[j]);
//
// var applicableTag = wffTagUtil.getTagByTagNameAndWffId(
// tagName, tagId);
//
// applicableTag.removeAttribute(attrName);
// console.log('attr removed');
// }
//
// }
// }
};
this.invokeTasks = function(wffBMBytes) {
var nameValues = wffBMUtil.parseWffBinaryMessageBytes(wffBMBytes);
var taskNameValue = nameValues[0];
if (taskNameValue.name[0] == wffGlobal.taskValues.TASK) {
console.log('TASK');
invokeTask(nameValues);
} else if (taskNameValue.name[0] == wffGlobal.taskValues.TASK_OF_TASKS) {
console.log('TASK_OF_TASKS');
var tasksBM = taskNameValue.values;
for (var i = 0; i < tasksBM.length; i++) {
var taskNameValues = wffBMUtil.parseWffBinaryMessageBytes(tasksBM[i]);
invokeTask(taskNameValues);
}
} else {
return false;
}
return true;
};
this.getAttributeUpdates = function(wffBMBytes) {
var nameValue = wffBMUtil.parseWffBinaryMessageBytes(wffBMBytes)[1];
};
}; | wffweb/src/main/resources/com/webfirmframework/wffweb/server/page/js/wffClientCRUDUtil.js | /**
*
*/
var wffClientCRUDUtil = new function() {
var encoder = wffGlobal.encoder;
var decoder = wffGlobal.decoder;
var getStringFromBytes = function(utf8Bytes) {
return decoder.decode(new Uint8Array(utf8Bytes));
};
var invokeTask = function(nameValues) {
var taskNameValue = nameValues[0];
// var taskName = getStringFromBytes(taskNameValue.name);
var taskValue = taskNameValue.values[0][0];
console.log('taskNameValue.name', taskNameValue.name);
if (taskValue == wffGlobal.taskValues.ATTRIBUTE_UPDATED) {
console.log('taskValue == "ATTRIBUTE_UPDATED"');
for (var i = 1; i < nameValues.length; i++) {
console.log('i', i);
console.log('nameValues[i].values', nameValues[i].values);
var attrNameValue = getStringFromBytes(nameValues[i].name);
console.log('attrNameValue', attrNameValue);
var indexOfSeparator = attrNameValue.indexOf('=');
var attrNameValueArry = wffTagUtil
.splitAttrNameValue(attrNameValue);
var attrName = attrNameValueArry[0];
var attrValue = attrNameValueArry[1];
// if (indexOfSeparator != -1) {
// attrName = attrNameValue.substring(0, indexOfSeparator);
// attrValue = attrNameValue.substring(indexOfSeparator + 1,
// attrNameValue.length);
// } else {
// attrName = attrNameValue;
// attrValue = '';
// }
console.log('attrName', attrName, 'attrValue', attrValue);
// var tagId = wffBMUtil
// .getIntFromOptimizedBytes(nameValues[i].name);
var wffIds = nameValues[i].values;
// var tagName = getStringFromBytes(wffIds[0]);
for (var j = 0; j < wffIds.length; j++) {
console.log('j', j);
var wffId = wffTagUtil.getWffIdFromWffIdBytes(wffIds[j]);
var applicableTag = wffTagUtil.getTagByWffId(wffId);
if (indexOfSeparator != -1) {
//value attribute doesn't work with setAttribute method
//should be called before setAttribute method
applicableTag[attrName] = attrValue;
applicableTag.setAttribute(attrName, attrValue);
} else {
//value attribute doesn't work with setAttribute method
//should be called before setAttribute method
applicableTag[attrName] = "";
applicableTag.setAttribute(attrName, "");
}
}
}
} else if (taskValue == wffGlobal.taskValues.REMOVED_ATTRIBUTE) {
console.log('taskValue == "REMOVED_ATTRIBUTE"');
for (var i = 1; i < nameValues.length; i++) {
console.log('i', i);
console.log('nameValues[i].values', nameValues[i].values);
var attrName = getStringFromBytes(nameValues[i].name);
console.log('attrName', attrName);
// var tagId = wffBMUtil
// .getIntFromOptimizedBytes(nameValues[i].name);
var wffIds = nameValues[i].values;
// var tagName = getStringFromBytes(wffIds[0]);
for (var j = 0; j < wffIds.length; j++) {
console.log('j', j);
var wffId = wffTagUtil.getWffIdFromWffIdBytes(wffIds[j]);
var applicableTag = wffTagUtil.getTagByWffId(wffId);
applicableTag.removeAttribute(attrName);
}
}
} else if (taskValue == wffGlobal.taskValues.APPENDED_CHILD_TAG
|| taskValue == wffGlobal.taskValues.APPENDED_CHILDREN_TAGS) {
// TODO comment this later
if (taskValue == wffGlobal.taskValues.APPENDED_CHILD_TAG) {
console.log('APPENDED_CHILD_TAG');
} else if (taskValue == wffGlobal.taskValues.APPENDED_CHILDREN_TAGS) {
console.log('APPENDED_CHILDREN_TAGS');
}
// end
for (var i = 1; i < nameValues.length; i++) {
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[i].name);
var values = nameValues[i].values;
var tagName = getStringFromBytes(values[0]);
var parent = wffTagUtil.getTagByTagNameAndWffId(tagName, wffId);
for (var j = 1; j < values.length; j++) {
// var htmlString = getStringFromBytes(values[j]);
// var div = document.createElement('div');
// div.innerHTML = htmlString;
// var htmlNodes = div.firstChild;
if (parent == undefined) {
console.log('parent == undefined', 'tagName', tagName,
'wffId', wffId);
}
var htmlNodes = wffTagUtil
.createTagFromWffBMBytes(values[j]);
parent.appendChild(htmlNodes);
}
}
} else if (taskValue == wffGlobal.taskValues.REMOVED_TAGS) {
console.log('wffGlobal.taskValues.REMOVED_TAGS nameValues.length '
+ nameValues.length);
for (var i = 1; i < nameValues.length; i++) {
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[i].name);
var values = nameValues[i].values;
var tagName = getStringFromBytes(values[0]);
var tagToRemove = wffTagUtil.getTagByTagNameAndWffId(tagName,
wffId);
console.log('tagToRemove', tagToRemove, 'tagName', tagName,
'wffId', wffId, 'count i', i);
var parent = tagToRemove.parentNode;
parent.removeChild(tagToRemove);
}
} else if (taskValue == wffGlobal.taskValues.REMOVED_ALL_CHILDREN_TAGS) {
console.log('wffGlobal.taskValues.REMOVED_ALL_CHILDREN_TAGS');
for (var i = 1; i < nameValues.length; i++) {
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[i].name);
var values = nameValues[i].values;
var tagName = getStringFromBytes(values[0]);
var parentTag = wffTagUtil.getTagByTagNameAndWffId(tagName,
wffId);
while (parentTag.firstChild) {
parentTag.removeChild(parentTag.firstChild);
}
}
} else if (taskValue == wffGlobal.taskValues.MOVED_CHILDREN_TAGS) {
console
.log('wffGlobal.taskValues.MOVED_CHILDREN_TAGS nameValues.length '
+ nameValues.length);
for (var i = 1; i < nameValues.length; i++) {
var currentParentWffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[i].name);
var values = nameValues[i].values;
var currentParentTagName = getStringFromBytes(values[0]);
var currentParentTag = wffTagUtil.getTagByTagNameAndWffId(
currentParentTagName, currentParentWffId);
var childWffId = wffTagUtil.getWffIdFromWffIdBytes(values[1]);
var childTagName = getStringFromBytes(values[2]);
var childTag = wffTagUtil.getTagByTagNameAndWffId(childTagName,
childWffId);
if (childTag !== undefined) {
var previousParent = childTag.parentNode;
console.log('childTag !== undefined', childTag);
previousParent.removeChild(childTag);
} else {
console.log('childTag === undefined', childTag);
childTag = wffTagUtil.createTagFromWffBMBytes(values[3]);
}
currentParentTag.appendChild(childTag);
}
} else if (taskValue == wffGlobal.taskValues.ADDED_ATTRIBUTES) {
console.log('taskValue == "ADDED_ATTRIBUTES"');
for (var i = 1; i < nameValues.length; i++) {
var nameValue = nameValues[i];
if (nameValue.name[0] == wffGlobal.taskValues.MANY_TO_ONE) {
var tagName = getStringFromBytes(nameValue.values[0]);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValue.values[1]);
var applicableTag = wffTagUtil.getTagByTagNameAndWffId(
tagName, wffId);
for (var j = 2; j < nameValue.values.length; j++) {
var attrNameValue = getStringFromBytes(nameValue.values[j]);
var attrNameValueArry = wffTagUtil
.splitAttrNameValue(attrNameValue);
var attrName = attrNameValueArry[0];
var attrValue = attrNameValueArry[1];
//value attribute doesn't work with setAttribute method
//should be called before setAttribute method
applicableTag[attrName] = attrValue;
applicableTag.setAttribute(attrName, attrValue);
}
}
}
} else if (taskValue == wffGlobal.taskValues.REMOVED_ATTRIBUTES) {
console.log('taskValue == "REMOVED_ATTRIBUTES"');
for (var i = 1; i < nameValues.length; i++) {
var nameValue = nameValues[i];
if (nameValue.name[0] == wffGlobal.taskValues.MANY_TO_ONE) {
var tagName = getStringFromBytes(nameValue.values[0]);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValue.values[1]);
var applicableTag = wffTagUtil.getTagByTagNameAndWffId(
tagName, wffId);
for (var j = 2; j < nameValue.values.length; j++) {
var attrName = getStringFromBytes(nameValue.values[j]);
applicableTag.removeAttribute(attrName);
}
}
}
} else if (taskValue == wffGlobal.taskValues.ADDED_INNER_HTML) {
console.log('wffGlobal.taskValues.ADDED_INNER_HTML');
var tagName = getStringFromBytes(nameValues[1].name);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[1].values[0]);
var parentTag = wffTagUtil.getTagByTagNameAndWffId(tagName,
wffId);
// it should be case sensitive node.innerHTML
// parentTag.innerHTML = innerHtml;
// inner html will not work with table
while (parentTag.firstChild) {
parentTag.removeChild(parentTag.firstChild);
}
for (var i = 2; i < nameValues.length; i++) {
var values = nameValues[i].values;
var htmlNodes = wffTagUtil.createTagFromWffBMBytes(nameValues[i].name);
//if length is 1 then there is an existing tag with this id
if (values.length == 1 && values[0].length == 1) {
console.log('values.length == 3');
var existingTag = wffTagUtil.getTagByTagNameAndWffId(
htmlNodes.nodeName, htmlNodes
.getAttribute("data-wff-id"));
if (existingTag) {
var parentOfExistingTag = existingTag.parentNode;
parentOfExistingTag.removeChild(existingTag);
}
}
parentTag.appendChild(htmlNodes);
}
} else if (taskValue == wffGlobal.taskValues.INSERTED_BEFORE_TAG) {
console.log('wffGlobal.taskValues.INSERTED_BEFORE_TAG');
for (var i = 1; i < nameValues.length; i++) {
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[i].name);
var values = nameValues[i].values;
var tagName = getStringFromBytes(values[0]);
// var innerHtml = getStringFromBytes(values[1]);
// console.log('innerHtml', innerHtml);
var parentTag = wffTagUtil.getTagByTagNameAndWffId(tagName,
wffId);
var beforeTagName = getStringFromBytes(values[2]);
var beforeTagWffId = wffTagUtil.getWffIdFromWffIdBytes(values[3]);
var beforeTag = wffTagUtil.getTagByTagNameAndWffId(beforeTagName,
beforeTagWffId);
var htmlNodes = wffTagUtil.createTagFromWffBMBytes(values[1]);
//if length is 3 then there is an existing tag with this id
if (values.length == 5) {
console.log('values.length == 5');
var existingTag = wffTagUtil.getTagByTagNameAndWffId(
htmlNodes.nodeName, htmlNodes
.getAttribute("data-wff-id"));
var parentOfExistingTag = existingTag.parentNode;
parentOfExistingTag.removeChild(existingTag);
}
parentTag.insertBefore(htmlNodes, beforeTag);
}
} else if (taskValue == wffGlobal.taskValues.RELOAD_BROWSER) {
location.reload(true);
} else if (taskValue == wffGlobal.taskValues.RELOAD_BROWSER_FROM_CACHE) {
location.reload();
} else if (taskValue == wffGlobal.taskValues.EXECURE_JS) {
var js = getStringFromBytes(taskNameValue.values[1]);
if (window.execScript) {
window.execScript(js);
} else {
eval(js);
}
} else if (taskValue == wffGlobal.taskValues.COPY_INNER_TEXT_TO_VALUE) {
console.log('wffGlobal.taskValues.COPY_INNER_TEXT_TO_VALUE');
var tagName = getStringFromBytes(nameValues[1].name);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[1].values[0]);
var parentTag = wffTagUtil.getTagByTagNameAndWffId(tagName,
wffId);
var d = document.createElement('div');
d.innerHTML = parentTag.outerHTML;
parentTag.value = d.childNodes[0].innerText;
} else if (taskValue == wffGlobal.taskValues.SET_BM_OBJ_ON_TAG
|| taskValue == wffGlobal.taskValues.SET_BM_ARR_ON_TAG) {
var tagName = getStringFromBytes(nameValues[1].name);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[1].values[0]);
var tag = wffTagUtil.getTagByTagNameAndWffId(tagName, wffId);
var ky = getStringFromBytes(nameValues[1].values[1]);
var bmObjOrArrBytes = nameValues[1].values[2];
var jsObjOrArr;
if (taskValue == wffGlobal.taskValues.SET_BM_OBJ_ON_TAG) {
jsObjOrArr = new JsObjectFromBMBytes(bmObjOrArrBytes, true);
} else {
jsObjOrArr = new JsArrayFromBMBytes(bmObjOrArrBytes, true);
}
var wffObjects = tag['wffObjects'];
if(typeof wffObjects === 'undefined') {
wffObjects = {};
tag['wffObjects'] = wffObjects;
}
wffObjects[ky] = jsObjOrArr;
} else if (taskValue == wffGlobal.taskValues.DEL_BM_OBJ_OR_ARR_FROM_TAG) {
var tagName = getStringFromBytes(nameValues[1].name);
var wffId = wffTagUtil
.getWffIdFromWffIdBytes(nameValues[1].values[0]);
var tag = wffTagUtil.getTagByTagNameAndWffId(tagName, wffId);
var ky = getStringFromBytes(nameValues[1].values[1]);
var wffObjects = tag['wffObjects'];
if(typeof wffObjects !== 'undefined') {
delete wffObjects[ky];
}
}
return true;
// else if (taskValue == 'DA') {
//
// for (var i = 1; i < nameValues.length; i++) {
//
// var tagId = wffBMUtil
// .getIntFromOptimizedBytes(nameValues[i].name);
// var attrNames = nameValues[i].values;
//
// var tagName = getStringFromBytes(attrNames[0]);
//
// for (var j = 1; j < attrNames.length; j++) {
//
// var attrName = getStringFromBytes(attrNames[j]);
//
// var applicableTag = wffTagUtil.getTagByTagNameAndWffId(
// tagName, tagId);
//
// applicableTag.removeAttribute(attrName);
// console.log('attr removed');
// }
//
// }
// }
};
this.invokeTasks = function(wffBMBytes) {
var nameValues = wffBMUtil.parseWffBinaryMessageBytes(wffBMBytes);
var taskNameValue = nameValues[0];
if (taskNameValue.name[0] == wffGlobal.taskValues.TASK) {
console.log('TASK');
invokeTask(nameValues);
} else if (taskNameValue.name[0] == wffGlobal.taskValues.TASK_OF_TASKS) {
console.log('TASK_OF_TASKS');
var tasksBM = taskNameValue.values;
for (var i = 0; i < tasksBM.length; i++) {
var taskNameValues = wffBMUtil.parseWffBinaryMessageBytes(tasksBM[i]);
invokeTask(taskNameValues);
}
} else {
return false;
}
return true;
};
this.getAttributeUpdates = function(wffBMBytes) {
var nameValue = wffBMUtil.parseWffBinaryMessageBytes(wffBMBytes)[1];
};
}; | Removed unwanted code | wffweb/src/main/resources/com/webfirmframework/wffweb/server/page/js/wffClientCRUDUtil.js | Removed unwanted code | <ide><path>ffweb/src/main/resources/com/webfirmframework/wffweb/server/page/js/wffClientCRUDUtil.js
<ide> } else if (taskValue == wffGlobal.taskValues.APPENDED_CHILD_TAG
<ide> || taskValue == wffGlobal.taskValues.APPENDED_CHILDREN_TAGS) {
<ide>
<del> // TODO comment this later
<del> if (taskValue == wffGlobal.taskValues.APPENDED_CHILD_TAG) {
<del> console.log('APPENDED_CHILD_TAG');
<del> } else if (taskValue == wffGlobal.taskValues.APPENDED_CHILDREN_TAGS) {
<del> console.log('APPENDED_CHILDREN_TAGS');
<del> }
<del> // end
<del>
<ide> for (var i = 1; i < nameValues.length; i++) {
<ide> var wffId = wffTagUtil
<ide> .getWffIdFromWffIdBytes(nameValues[i].name); |
|
Java | mit | 6c54a49c1c37f028e65eb04458ccc4c6a89a74c5 | 0 | v3rm0n/fratpos,v3rm0n/fratpos,v3rm0n/fratpos | package ee.leola.kassa.controllers.rest;
import ee.leola.kassa.helpers.Json;
import ee.leola.kassa.models.*;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.Set;
/**
* Created by vermon on 06/04/14.
*/
@Path("/stocktaking")
public class Stocktakings extends RestController<Stocktaking> {
@Override
protected Class<Stocktaking> getModelClass() {
return Stocktaking.class;
}
@GET
@Path("/csv/{id}")
@Produces("text/csv")
public Response getCSV(@PathParam("id") Long id) throws IOException {
Stocktaking stocktaking = Model.byId(Stocktaking.class, id);
StringBuilder template = new StringBuilder("Inventuur\n");
template.append("Loomise aeg ").append(stocktaking.getFormattedTime()).append("\n\n");
template.append("Kasutajad\nStaatus,Eesnimi,Perenimi,Õllenimi,Saldo\n");
stocktaking.getUsers().forEach(user -> {
template.append(String.format("%s,%s,%s,%s,%s\n",
user.get("status").get("name").asText(),
user.get("firstName").asText(),
user.get("lastName").asText(),
user.get("beerName").asText(),
user.get("balance").asText()));
});
template.append(",,,Summa,").append(stocktaking.getBalancesSum()).append("\n\n");
template.append("Tehingud\nAeg,Nimi,Summa,Makseviis,Katkestatud\n");
stocktaking.getTransactions().forEach(transaction -> {
template.append(String.format("%s,%s,%s,%s,%s\n",
transaction.get("formattedTime").asText(),
transaction.get("user").get("label").asText(),
transaction.get("sum").asText(),
transaction.get("paytype").get("name").asText(),
transaction.get("invalid").asBoolean() ? "Jah" : "Ei"));
});
template.append(",Summa,").append(stocktaking.getTransactionsSum()).append("\n\n");
template.append("Laoseis\nNimi,Hind,Kogus\n");
stocktaking.getProducts().forEach(product -> {
template.append(String.format("%s,%s,%s\n",
product.get("name").asText(),
product.get("price").asText(),
product.get("quantity").asText()));
});
template.append(",Kokku,").append(stocktaking.getProductsQuantity());
return ok(template.toString());
}
@POST
@Path("/{id}")
@Override
public Response update(Stocktaking s) {
return Response.status(Response.Status.METHOD_NOT_ALLOWED).build();
}
@POST
@Override
public Response create(Stocktaking s) {
Stocktaking stocktaking = new Stocktaking();
Set<User> users = User.find().where("balance <> 0").findSet();
stocktaking.setUsers(Json.toJson(users).toString());
Set<Transaction> transactions = Transaction.find().findSet();
stocktaking.setTransactions(Json.toJson(transactions).toString());
transactions.forEach(transaction -> transaction.delete());
Set<Product> products = Product.find().findSet();
stocktaking.setProducts(Json.toJson(products).toString());
stocktaking.save();
return ok(stocktaking.toJson());
}
}
| src/main/java/ee/leola/kassa/controllers/rest/Stocktakings.java | package ee.leola.kassa.controllers.rest;
import ee.leola.kassa.helpers.Json;
import ee.leola.kassa.models.Product;
import ee.leola.kassa.models.Stocktaking;
import ee.leola.kassa.models.Transaction;
import ee.leola.kassa.models.User;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import java.util.Set;
/**
* Created by vermon on 06/04/14.
*/
@Path("/stocktaking")
public class Stocktakings extends RestController<Stocktaking> {
@Override
protected Class<Stocktaking> getModelClass() {
return Stocktaking.class;
}
@GET
@Path("/csv/{id}")
public Response getCSV(@PathParam("id") Long id) {
return Response.serverError().build();
}
@POST
@Path("/{id}")
@Override
public Response update(Stocktaking s) {
return Response.status(Response.Status.METHOD_NOT_ALLOWED).build();
}
@POST
@Override
public Response create(Stocktaking s) {
Stocktaking stocktaking = new Stocktaking();
Set<User> users = User.find().where("balance <> 0").findSet();
stocktaking.setUsers(Json.toJson(users).toString());
Set<Transaction> transactions = Transaction.find().findSet();
stocktaking.setTransactions(Json.toJson(transactions).toString());
transactions.forEach(transaction -> transaction.delete());
Set<Product> products = Product.find().findSet();
stocktaking.setProducts(Json.toJson(products).toString());
stocktaking.save();
return ok(stocktaking.toJson());
}
}
| Stocktaking as CSV
| src/main/java/ee/leola/kassa/controllers/rest/Stocktakings.java | Stocktaking as CSV | <ide><path>rc/main/java/ee/leola/kassa/controllers/rest/Stocktakings.java
<ide> package ee.leola.kassa.controllers.rest;
<ide>
<ide> import ee.leola.kassa.helpers.Json;
<del>import ee.leola.kassa.models.Product;
<del>import ee.leola.kassa.models.Stocktaking;
<del>import ee.leola.kassa.models.Transaction;
<del>import ee.leola.kassa.models.User;
<add>import ee.leola.kassa.models.*;
<ide>
<del>import javax.ws.rs.GET;
<del>import javax.ws.rs.POST;
<del>import javax.ws.rs.Path;
<del>import javax.ws.rs.PathParam;
<add>import javax.ws.rs.*;
<ide> import javax.ws.rs.core.Response;
<add>import java.io.IOException;
<ide> import java.util.Set;
<ide>
<ide> /**
<ide>
<ide> @GET
<ide> @Path("/csv/{id}")
<del> public Response getCSV(@PathParam("id") Long id) {
<del> return Response.serverError().build();
<add> @Produces("text/csv")
<add> public Response getCSV(@PathParam("id") Long id) throws IOException {
<add> Stocktaking stocktaking = Model.byId(Stocktaking.class, id);
<add> StringBuilder template = new StringBuilder("Inventuur\n");
<add> template.append("Loomise aeg ").append(stocktaking.getFormattedTime()).append("\n\n");
<add>
<add> template.append("Kasutajad\nStaatus,Eesnimi,Perenimi,Õllenimi,Saldo\n");
<add> stocktaking.getUsers().forEach(user -> {
<add> template.append(String.format("%s,%s,%s,%s,%s\n",
<add> user.get("status").get("name").asText(),
<add> user.get("firstName").asText(),
<add> user.get("lastName").asText(),
<add> user.get("beerName").asText(),
<add> user.get("balance").asText()));
<add> });
<add> template.append(",,,Summa,").append(stocktaking.getBalancesSum()).append("\n\n");
<add>
<add> template.append("Tehingud\nAeg,Nimi,Summa,Makseviis,Katkestatud\n");
<add> stocktaking.getTransactions().forEach(transaction -> {
<add> template.append(String.format("%s,%s,%s,%s,%s\n",
<add> transaction.get("formattedTime").asText(),
<add> transaction.get("user").get("label").asText(),
<add> transaction.get("sum").asText(),
<add> transaction.get("paytype").get("name").asText(),
<add> transaction.get("invalid").asBoolean() ? "Jah" : "Ei"));
<add> });
<add> template.append(",Summa,").append(stocktaking.getTransactionsSum()).append("\n\n");
<add>
<add> template.append("Laoseis\nNimi,Hind,Kogus\n");
<add> stocktaking.getProducts().forEach(product -> {
<add> template.append(String.format("%s,%s,%s\n",
<add> product.get("name").asText(),
<add> product.get("price").asText(),
<add> product.get("quantity").asText()));
<add> });
<add> template.append(",Kokku,").append(stocktaking.getProductsQuantity());
<add> return ok(template.toString());
<ide> }
<ide>
<ide> @POST |
|
Java | apache-2.0 | 8fe0b837aab21eadf714c509e70d7f23cc9bbf19 | 0 | pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus | /**
* Copyright 2007-2008 University Of Southern California
*
* 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 edu.isi.pegasus.planner.refiner;
import edu.isi.pegasus.planner.catalog.site.classes.FileServer;
import edu.isi.pegasus.planner.catalog.site.classes.SiteCatalogEntry;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.planner.classes.ADag;
import edu.isi.pegasus.planner.classes.FileTransfer;
import edu.isi.pegasus.planner.classes.NameValue;
import edu.isi.pegasus.planner.classes.PegasusFile;
import edu.isi.pegasus.planner.classes.ReplicaLocation;
import edu.isi.pegasus.planner.classes.Job;
import edu.isi.pegasus.planner.classes.PegasusBag;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.planner.namespace.Pegasus;
import edu.isi.pegasus.planner.partitioner.graph.GraphNode;
import edu.isi.pegasus.planner.partitioner.graph.Graph;
import edu.isi.pegasus.planner.partitioner.graph.Adapter;
import edu.isi.pegasus.planner.selector.ReplicaSelector;
import edu.isi.pegasus.planner.selector.replica.ReplicaSelectorFactory;
import edu.isi.pegasus.planner.transfer.Refiner;
import edu.isi.pegasus.planner.transfer.refiner.RefinerFactory;
import edu.isi.pegasus.planner.catalog.ReplicaCatalog;
import edu.isi.pegasus.planner.catalog.replica.ReplicaCatalogEntry;
import edu.isi.pegasus.common.util.FactoryException;
import edu.isi.pegasus.common.util.PegasusURL;
import edu.isi.pegasus.planner.catalog.replica.ReplicaFactory;
import edu.isi.pegasus.planner.catalog.site.classes.Directory;
import edu.isi.pegasus.planner.catalog.site.classes.FileServerType.OPERATION;
import edu.isi.pegasus.planner.classes.DAGJob;
import edu.isi.pegasus.planner.classes.DAXJob;
import edu.isi.pegasus.planner.classes.PlannerCache;
import edu.isi.pegasus.planner.classes.PlannerOptions;
import edu.isi.pegasus.planner.common.PegasusConfiguration;
import edu.isi.pegasus.planner.namespace.Dagman;
import org.griphyn.vdl.euryale.FileFactory;
import org.griphyn.vdl.euryale.VirtualDecimalHashedFileFactory;
import org.griphyn.vdl.euryale.VirtualFlatFileFactory;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.Properties;
/**
* The transfer engine, which on the basis of the pools on which the jobs are to
* run, adds nodes to transfer the data products.
*
* @author Karan Vahi
* @author Gaurang Mehta
* @version $Revision$
*
*/
public class TransferEngine extends Engine {
/**
* The MAX level is assigned as the level for deleted jobs.
* We can put it to Integer.MAX_VALUE, but it is rare that number of levels
* in a workflows exceed 1000.
*/
public static final int DELETED_JOBS_LEVEL = 1000;
/**
* The name of the Replica Catalog Implementer that is used to write out
* the workflow cache file in the submit directory.
*/
public static final String WORKFLOW_CACHE_FILE_IMPLEMENTOR = "FlushedCache";
/**
* The name of the source key for Replica Catalog Implementer that serves as
* cache
*/
public static final String WORKFLOW_CACHE_REPLICA_CATALOG_KEY = "file";
/**
* The property prefix for retrieving SRM properties.
*/
public static final String SRM_PROPERTIES_PREFIX = "pegasus.transfer.srm";
/**
* The suffix to retrive the service url for SRM server.
*/
public static final String SRM_SERVICE_URL_PROPERTIES_SUFFIX = "service.url";
/**
* The suffix to retrive the mount point for SRM server.
*/
public static final String SRM_MOUNT_POINT_PROPERTIES_SUFFIX = "mountpoint";
/**
* The name of the refiner for purposes of error logging
*/
public static final String REFINER_NAME = "TranferEngine";
/**
* A map that associates the site name with the SRM server url and mount point.
*/
private Map<String, NameValue> mSRMServiceURLToMountPointMap;
/**
* The DAG object to which the transfer nodes are to be added. This is the
* reduced Dag, which is got from the Reduction Engine.
*/
private ADag mDag;
/**
* The bridge to the Replica Catalog.
*/
private ReplicaCatalogBridge mRCBridge;
/**
* The handle to the replica selector that is to used to select the various
* replicas.
*/
private ReplicaSelector mReplicaSelector;
/**
* The handle to the transfer refiner that adds the transfer nodes into the
* workflow.
*/
private Refiner mTXRefiner;
/**
* Holds all the jobs deleted by the reduction algorithm.
*/
private List mDeletedJobs;
/**
* A SimpleFile Replica Catalog, that tracks all the files that are being
* materialized as part of workflow executaion.
*/
private PlannerCache mPlannerCache;
/**
* A Replica Catalog, that tracks all the GET URL's for the files on the
* staging sites.
*/
private ReplicaCatalog mWorkflowCache;
/**
* The handle to the file factory, that is used to create the top level
* directories for each of the partitions.
*/
private FileFactory mFactory;
/**
* The Directory on the output site as retrieved from the site catalog.
*/
private Directory mStageoutDirectory;
/**
* The working directory relative to the mount point of the execution pool.
* It is populated from the pegasus.dir.exec property from the properties file.
* If not specified then it work_dir is supposed to be the exec mount point
* of the execution pool.
*/
protected String mWorkDir;
/**
* A boolean indicating whether to have a deep directory structure for
* the storage directory or not.
*/
protected boolean mDeepStorageStructure;
/**
* This member variable if set causes the destination URL for the symlink jobs
* to have symlink:// url if the pool attributed associated with the pfn
* is same as a particular jobs execution pool.
*/
protected boolean mUseSymLinks;
/**
* A boolean indicating whether we are doing worker node execution or not.
*/
private boolean mWorkerNodeExecution;
/**
* The planner options passed to the planner
*/
private PlannerOptions mPlannerOptions;
/**
* A boolean indicating whether to bypass first level staging for inputs
*/
private boolean mBypassStagingForInputs;
/**
* A boolean to track whether condor file io is used for the workflow or not.
*/
private final boolean mSetupForCondorIO;
/**
* Overloaded constructor.
*
* @param reducedDag the reduced workflow.
* @param bag bag of initialization objects
* @param deletedJobs list of all jobs deleted by reduction algorithm.
* @param deletedLeafJobs list of deleted leaf jobs by reduction algorithm.
*/
public TransferEngine( ADag reducedDag,
PegasusBag bag,
List<Job> deletedJobs ,
List<Job> deletedLeafJobs){
super( bag );
mPlannerOptions = bag.getPlannerOptions();
mDeepStorageStructure = mProps.useDeepStorageDirectoryStructure();
mUseSymLinks = mProps.getUseOfSymbolicLinks();
mSRMServiceURLToMountPointMap = constructSiteToSRMServerMap( mProps );
mDag = reducedDag;
mDeletedJobs = deletedJobs;
mWorkerNodeExecution = mProps.executeOnWorkerNode();
mSetupForCondorIO = new PegasusConfiguration( mLogger).setupForCondorIO( mProps );
mBypassStagingForInputs = mProps.bypassFirstLevelStagingForInputs();
try{
mTXRefiner = RefinerFactory.loadInstance( reducedDag,
bag );
mReplicaSelector = ReplicaSelectorFactory.loadInstance(mProps);
}
catch(Exception e){
//wrap all the exceptions into a factory exception
throw new FactoryException("Transfer Engine ", e);
}
this.initializeStageOutSiteDirectoryFactory( reducedDag );
mWorkflowCache = this.initializeWorkflowCacheFile( reducedDag );
//log some configuration messages
mLogger.log("Transfer Refiner loaded is [" + mTXRefiner.getDescription() +
"]",LogManager.CONFIG_MESSAGE_LEVEL);
mLogger.log("ReplicaSelector loaded is [" + mReplicaSelector.description() +
"]",LogManager.CONFIG_MESSAGE_LEVEL);
}
/**
* Returns whether to run a transfer job on local site or not.
*
*
* @param site the site handle associated with the destination URL.
* @param destPutURL the destination URL
* @param type the type of transfer job for which the URL is being constructed.
*
* @return true indicating if the associated transfer job should run on local
* site or not.
*/
public boolean runTransferOnLocalSite( String site, String destinationURL, int type) {
//check if user has specified any preference in config
boolean result = true;
//short cut for local site
if( site.equals( "local" ) ){
//transfer to run on local site
return result;
}
if( mTXRefiner.refinerPreferenceForTransferJobLocation() ){
//refiner is advertising a preference for where transfer job
//should be run. Use that.
return mTXRefiner.refinerPreferenceForLocalTransferJobs( type );
}
if( mTXRefiner.runTransferRemotely( site, type )){
//always use user preference
return !result;
}
//check to see if destination URL is a file url
else if( destinationURL != null && destinationURL.startsWith( PegasusURL.FILE_URL_SCHEME ) ){
result = false;
}
return result;
}
/**
* Adds the transfer nodes to the workflow.
*
* @param rcb the bridge to the ReplicaCatalog.
* @param plannerCache an instance of the replica catalog that will
* store the locations of the files on the remote
* sites.
*/
public void addTransferNodes( ReplicaCatalogBridge rcb, PlannerCache plannerCache ) {
mRCBridge = rcb;
mPlannerCache = plannerCache;
Job currentJob;
String currentJobName;
Vector vOutPoolTX;
String msg;
String outputSite = mPOptions.getOutputSite();
//convert the dax to a graph representation and walk it
//in a top down manner
Graph workflow = Adapter.convert( mDag );
//go through each job in turn
boolean stageOut = (( outputSite != null ) && ( outputSite.trim().length() > 0 ));
for( Iterator it = workflow.iterator(); it.hasNext(); ){
GraphNode node = ( GraphNode )it.next();
currentJob = (Job)node.getContent();
//set the staging site for the job
//currentJob.setStagingSiteHandle( getStagingSite( currentJob ) );
//set the node depth as the level
currentJob.setLevel( node.getDepth() );
currentJobName = currentJob.getName();
mLogger.log("",LogManager.DEBUG_MESSAGE_LEVEL);
msg = "Job being traversed is " + currentJobName;
mLogger.log(msg, LogManager.DEBUG_MESSAGE_LEVEL);
msg = "To be run at " + currentJob.executionPool;
mLogger.log(msg, LogManager.DEBUG_MESSAGE_LEVEL);
//getting the parents of that node
List<GraphNode> parents = node.getParents();
mLogger.log("Parents of job:" + node.parentsToString(),
LogManager.DEBUG_MESSAGE_LEVEL);
processParents(currentJob, parents);
//transfer the nodes output files
//to the output pool
if ( stageOut ) {
SiteCatalogEntry stagingSite = mSiteStore.lookup( currentJob.getStagingSiteHandle() );
if (stagingSite == null ) {
mLogMsg = this.poolNotFoundMsg( currentJob.getSiteHandle(), "vanilla");
mLogger.log( mLogMsg, LogManager.ERROR_MESSAGE_LEVEL );
throw new RuntimeException( mLogMsg );
}
//PM-590 Stricter checks
String stagingSiteURLPrefix = stagingSite.selectHeadNodeScratchSharedFileServerURLPrefix( FileServer.OPERATION.put );
if( stagingSiteURLPrefix == null ){
this.complainForHeadNodeURLPrefix( REFINER_NAME, stagingSite.getSiteHandle(), FileServer.OPERATION.put, currentJob );
}
boolean localTransfer = runTransferOnLocalSite(
currentJob.getSiteHandle(),
stagingSiteURLPrefix,
Job.STAGE_OUT_JOB);
vOutPoolTX = getFileTX(outputSite, currentJob, localTransfer );
mTXRefiner.addStageOutXFERNodes( currentJob, vOutPoolTX, rcb, localTransfer );
}
else{
//create the cache file always
//Pegasus Bug PM-32 and PM-356
trackInCaches( currentJob );
}
}
//we are done with the traversal.
//mTXRefiner.done();
//get the deleted leaf jobs o/p files to output pool
//only if output pool is specified
//should be moved upwards in the pool. redundancy at present
if (outputSite != null &&
outputSite.trim().length() > 0
&& !mDeletedJobs.isEmpty() ) {
mLogger.log( "Adding stage out jobs for jobs deleted from the workflow", LogManager.INFO_MESSAGE_LEVEL );
for( Iterator it = this.mDeletedJobs.iterator(); it.hasNext() ;) {
currentJob = (Job)it.next();
currentJob.setLevel( TransferEngine.DELETED_JOBS_LEVEL );
//for a deleted node, to transfer it's output
//the execution pool should be set to local i.e submit host
currentJob.setSiteHandle( "local" );
//set the staging site for the deleted job
currentJob.setStagingSiteHandle( getStagingSite( currentJob ) );
//for jobs deleted during data reuse we dont
//go through the staging site. they are transferred
//directly to the output site.
vOutPoolTX = getDeletedFileTX(outputSite, currentJob);
if( !vOutPoolTX.isEmpty() ){
//the job is deleted anyways. The files exist somewhere
//as mentioned in the Replica Catalog. We assume it is
//URL remotely accessible
boolean localTransfer = true;
mTXRefiner.addStageOutXFERNodes( currentJob, vOutPoolTX, rcb, localTransfer, true );
}
}
}
//we are done with the traversal.
mTXRefiner.done();
//close the handle to the workflow cache file if it is written
//not the planner cache file
this.mWorkflowCache.close();
}
/**
* Returns the staging site to be used for a job. If a staging site is not
* determined from the options it is set to be the execution site for the job
*
* @param job the job for which to determine the staging site
*
* @return the staging site
*/
public String getStagingSite( Job job ){
String ss = this.mPOptions.getStagingSite( job.getSiteHandle() );
return (ss == null) ? job.getSiteHandle(): ss;
}
/**
* This gets the file transfer objects corresponding to the location of files
* found in the replica mechanism, and transfers it to the output pool asked
* by the user. If the output pool path and the one returned by the replica
* mechanism match then that object is not transferred.
*
* @param pool this the output pool which the user specifies at runtime.
* @param job The Job object corresponding to the leaf job which was
* deleted by the Reduction algorithm
*
* @return Vector of <code>FileTransfer</code> objects
*/
private Vector getDeletedFileTX( String pool, Job job ) {
Vector vFileTX = new Vector();
for( Iterator it = job.getOutputFiles().iterator(); it.hasNext(); ){
PegasusFile pf = (PegasusFile)it.next();
String lfn = pf.getLFN();
//we only have to get a deleted file that user wants to be transferred
if( pf.getTransientTransferFlag() ){
continue;
}
ReplicaLocation rl = mRCBridge.getFileLocs( lfn );
//sanity check
if( rl == null ){
throw new RuntimeException( "Unable to find a location in the Replica Catalog for output file " + lfn );
}
String putDestURL = getURLOnStageoutSite( mStageoutDirectory, FileServer.OPERATION.put, lfn );
String getDestURL = getURLOnStageoutSite( mStageoutDirectory, FileServer.OPERATION.get, lfn );
//selLocs are all the locations found in ReplicaMechanism corr
//to the pool pool
ReplicaLocation selLocs = mReplicaSelector.selectReplicas( rl,
pool,
this.runTransferOnLocalSite( pool,putDestURL, Job.STAGE_OUT_JOB ));
boolean flag = false;
FileTransfer ft = null;
//checking through all the pfn's returned on the pool
for ( Iterator selIt = selLocs.pfnIterator(); selIt.hasNext(); ) {
ReplicaCatalogEntry selLoc = ( ReplicaCatalogEntry ) selIt.next();
String sourceURL = selLoc.getPFN();
//check if the URL's match
if (sourceURL.trim().equalsIgnoreCase(putDestURL.trim())){
String msg = "The leaf file " + lfn +
" is already at the output pool " + pool;
mLogger.log(msg,LogManager.INFO_MESSAGE_LEVEL);
flag = true;
break;
}
ft = new FileTransfer( lfn, job.getName() );
ft.addSource( selLoc.getResourceHandle() , sourceURL );
ft.addDestination( pool, putDestURL );
ft.setURLForRegistrationOnDestination( getDestURL );
ft.setSize( pf.getSize() );
//System.out.println("Deleted Leaf Job File transfer object " + ft);
}
if (!flag) { // adding the last pfn
vFileTX.addElement(ft);
}
}
return vFileTX;
}
/**
* It processes a nodes parents and determines if nodes are to be added
* or not. All the input files for the job are searched in the output files of
* the parent nodes and the Replica Mechanism.
*
* @param job the <code>Job</code> object containing all the
* details of the job.
* @param parents list <code>GraphNode</code> ojbects corresponding to the parent jobs
* of the job.
*/
private void processParents(Job job, List<GraphNode> parents) {
Set nodeIpFiles = job.getInputFiles();
Vector vRCSearchFiles = new Vector(); //vector of PegasusFile
//getAll the output Files of the parents
Set<PegasusFile> parentsOutFiles = getOutputFiles( parents );
//interpool transfer of the nodes parents
//output files
Collection[] interSiteFileTX = this.getInterpoolFileTX(job, parents);
Collection localInterSiteTX = interSiteFileTX[0];
Collection remoteInterSiteTX = interSiteFileTX[1];
//only add if there are files to transfer
if( !localInterSiteTX.isEmpty()){
mTXRefiner.addInterSiteTXNodes(job, localInterSiteTX, true );
}
if( !remoteInterSiteTX.isEmpty() ){
mTXRefiner.addInterSiteTXNodes(job, remoteInterSiteTX, false );
}
//check if node ip files are in the parents out files
//if files are not, then these are to be got
//from the RC based on the transiency characteristic
for( Iterator it = nodeIpFiles.iterator(); it.hasNext(); ){
PegasusFile pf = (PegasusFile) it.next();
if( !parentsOutFiles.contains( pf ) ){
if (!pf.getTransientTransferFlag()) {
vRCSearchFiles.addElement(pf);
}
}
}
if (!vRCSearchFiles.isEmpty()) {
if( job instanceof DAXJob ){
getFilesFromRC( (DAXJob)job, vRCSearchFiles);
}
else if( job instanceof DAGJob ){
getFilesFromRC( (DAGJob)job, vRCSearchFiles);
}
else{
//get the locations from the RC
getFilesFromRC(job, vRCSearchFiles);
}
}
}
/**
* This gets the Vector of FileTransfer objects for the files which have to
* be transferred to an one destination pool. It checks for the transient
* flags for files. If the transfer transient flag is set, it means the file
* does not have to be transferred to the destination pool.
*
* @param destSiteHandle The pool to which the files are to be transferred to.
* @param job The <code>Job</code>object of the job whose output files
* are needed at the destination pool.
* @param localTransfer boolean indicating that associated transfer job will run
* on local site.
*
* @return Vector of <code>FileTransfer</code> objects
*/
private Vector getFileTX(String destPool, Job job, boolean localTransfer ) {
Vector vFileTX = new Vector();
//check if there is a remote initialdir set
String path = job.vdsNS.getStringValue(
Pegasus.REMOTE_INITIALDIR_KEY );
for( Iterator it = job.getOutputFiles().iterator(); it.hasNext(); ){
PegasusFile pf = (PegasusFile) it.next();
String file = pf.getLFN();
FileTransfer ft = this.constructFileTX( pf,
job,
destPool,
path,
localTransfer );
if (ft != null) {
vFileTX.add(ft);
}
}
return vFileTX;
}
/**
* Constructs the FileTransfer object on the basis of the transiency
* information. If the transient flag for transfer is set, the destPutURL for the
* FileTransfer object would be the execution directory, as this is the entry
* that has to be registered in the ReplicaMechanism
*
* @param pf the PegasusFile for which the transfer has to be done.
* @param stagingSiteHandle the staging site at which file is placed after execution.
* @param destSiteHandle the output pool where the job should be transferred
* @param job the name of the associated job.
* @param path the path that a user specifies in the profile for key
* remote_initialdir that results in the workdir being
* changed for a job on a execution pool.
* @param localTransfer boolean indicating that associated transfer job will run
* on local site.
*
* @return the corresponding FileTransfer object
*/
private FileTransfer constructFileTX( PegasusFile pf,
Job job,
String destSiteHandle,
String path,
boolean localTransfer ) {
String stagingSiteHandle = job.getStagingSiteHandle();
String lfn = pf.getLFN();
FileTransfer ft = null;
SiteCatalogEntry stagingSite = mSiteStore.lookup( stagingSiteHandle );
SiteCatalogEntry destinationSite = mSiteStore.lookup( destSiteHandle );
if (stagingSite == null || destinationSite == null) {
mLogMsg = (stagingSite == null) ?
this.poolNotFoundMsg(stagingSiteHandle, "vanilla") :
this.poolNotFoundMsg(destSiteHandle, "vanilla");
mLogger.log( mLogMsg, LogManager.ERROR_MESSAGE_LEVEL );
throw new RuntimeException( mLogMsg );
}
//the get
String sharedScratchGetURL = this.getURLOnSharedScratch( stagingSite, job, OPERATION.get, lfn );
String sharedScratchPutURL = this.getURLOnSharedScratch( stagingSite, job, OPERATION.put, lfn );
/*
FileServer stagingSiteSharedScratchFS = stagingSite.selectHeadNodeScratchSharedFileServer( FileServer.OPERATION.put );
if( stagingSiteSharedScratchFS == null ){
this.complainForScratchFileServer( job, FileServer.OPERATION.put, stagingSiteHandle );
}
StringBuffer buffer = new StringBuffer();
buffer.append( stagingSiteSharedScratchFS.getURLPrefix() ).
append( mSiteStore.getExternalWorkDirectory(stagingSiteSharedScratchFS, stagingSiteHandle)).
append( File.separatorChar ).append( lfn );
String sharedScratchGetURL = buffer.toString();
*/
//in the planner cache we track the output files put url on staging site
trackInPlannerCache( lfn, sharedScratchPutURL, stagingSiteHandle );
//in the workflow cache we track the output files put url on staging site
trackInWorkflowCache( lfn, sharedScratchGetURL, stagingSiteHandle );
//if both transfer and registration
//are transient return null
if (pf.getTransientRegFlag() && pf.getTransientTransferFlag()) {
return null;
}
//if only transient transfer flag
//means destPutURL and sourceURL
//are same and are equal to
//execution directory on stagingSiteHandle
if (pf.getTransientTransferFlag()) {
ft = new FileTransfer(lfn,job.getID(),pf.getFlags());
//set the transfer mode
ft.setSize( pf.getSize() );
ft.setTransferFlag(pf.getTransferFlag());
ft.addSource(stagingSiteHandle,sharedScratchGetURL);
ft.addDestination(stagingSiteHandle,sharedScratchGetURL);
ft.setURLForRegistrationOnDestination( sharedScratchGetURL );
}
//the source dir is the exec dir
//on exec pool and dest dir
//would be on the output pool
else {
//construct the source url depending on whether third party tx
String sourceURL = localTransfer ?
sharedScratchGetURL :
"file://" + mSiteStore.getInternalWorkDirectory(stagingSiteHandle,path) +
File.separator + lfn;
ft = new FileTransfer(lfn, job.getID(), pf.getFlags());
ft.setSize( pf.getSize() );
//set the transfer mode
ft.setTransferFlag(pf.getTransferFlag());
ft.addSource(stagingSiteHandle,sourceURL);
//if the PegasusFile is already an instance of
//FileTransfer the user has specified the destination
//that they want to use in the DAX 3.0
if( pf instanceof FileTransfer ){
//not really supported in DAX 3.3?
ft.addDestination( ((FileTransfer)pf).removeDestURL() );
return ft;
}
//add all the possible destination urls iterating through
//the list of grid ftp servers associated with the dest pool.
// Iterator it = mSiteStore.lookup( destSiteHandle ).getHeadNodeFS().getStorage().getSharedDirectory().getFileServersIterator();
Directory storageDirectory = mSiteStore.lookup( destSiteHandle ).getHeadNodeStorageDirectory();
if( storageDirectory == null ){
throw new RuntimeException( "No Storage directory specified for site " + destSiteHandle );
}
//sanity check
if( !storageDirectory.hasFileServerForPUTOperations() ){
//no file servers for put operations
throw new RuntimeException( " No File Servers specified for PUT Operation on Shared Storage on Headnode for site " + destSiteHandle );
}
for( FileServer.OPERATION op : FileServer.OPERATION.operationsForPUT() ){
for( Iterator it = storageDirectory.getFileServersIterator(op); it.hasNext();){
FileServer fs = (FileServer)it.next();
//file server on output site
String destURL = this.getURLOnStageoutSite( fs, lfn);
//if the paths match of dest URI
//and execDirURL we return null
if (sharedScratchGetURL.equalsIgnoreCase(destURL)) {
/*ft = new FileTransfer(file, job);
ft.addSource(stagingSiteHandle, sharedScratchGetURL);*/
ft.addDestination(stagingSiteHandle, sharedScratchGetURL);
ft.setURLForRegistrationOnDestination( sharedScratchGetURL );
//make the transfer transient?
ft.setTransferFlag(PegasusFile.TRANSFER_NOT);
return ft;
}
ft.addDestination( destSiteHandle, destURL );
}
}//end of different put operations
//construct a registration URL
ft.setURLForRegistrationOnDestination( constructRegistrationURL( storageDirectory ,destSiteHandle, lfn ) );
}
return ft;
}
/**
* Constructs a Registration URL for a LFN
*
* @param directory the storage directory
* @param site the site handle
* @param lfn the LFN for which the URL needs to be constructed
*
* @return the URL
*/
private String constructRegistrationURL( Directory directory , String site, String lfn ){
//sanity check
if( !directory.hasFileServerForGETOperations() ){
//no file servers for GET operations
throw new RuntimeException( " No File Servers specified for GET Operation on Shared Storage for site " + site );
}
String url = null;
for( FileServer.OPERATION op : FileServer.OPERATION.operationsForGET() ){
for( Iterator it = directory.getFileServersIterator(op); it.hasNext();){
FileServer fs = (FileServer)it.next();
//assumption of same external mount point for each storage
//file server on output site
url = this.getURLOnStageoutSite( fs, lfn );
return url;
}
}//end of different get operations
return url;
}
/**
* This generates a error message for pool not found in the pool
* config file.
*
* @param poolName the name of pool that is not found.
* @param universe the condor universe
*
* @return the message.
*/
private String poolNotFoundMsg(String poolName, String universe) {
String st = "Error: No matching entry to pool = " + poolName +
" ,universe = " + universe +
"\n found in the pool configuration file ";
return st;
}
/**
* This gets the Vector of FileTransfer objects for all the files which have
* to be transferred to the destination pool in case of Interpool transfers.
* Each FileTransfer object has the source and the destination URLs. the
* source URI is determined from the pool on which the jobs are executed.
*
* @param job the job with reference to which interpool file transfers
* need to be determined.
* @param parents list <code>GraphNode</code> ojbects corresponding to the
* parent jobs of the job.
*
* @return array of Collection of <code>FileTransfer</code> objects
*/
private Collection<FileTransfer>[] getInterpoolFileTX(Job job, List<GraphNode>parents ) {
String destSiteHandle = job.getStagingSiteHandle();
//contains the remote_initialdir if specified for the job
String destRemoteDir = job.vdsNS.getStringValue(
Pegasus.REMOTE_INITIALDIR_KEY);
SiteCatalogEntry destSite = mSiteStore.lookup( destSiteHandle );
SiteCatalogEntry sourceSite;
Collection[] result = new Collection[2];
Collection<FileTransfer> localTransfers = new LinkedList();
Collection<FileTransfer> remoteTransfers = new LinkedList();
for ( GraphNode parent: parents ) {
//get the parent job
Job pJob = (Job)parent.getContent();
sourceSite = mSiteStore.lookup( pJob.getStagingSiteHandle() );
if( sourceSite.getSiteHandle().equalsIgnoreCase( destSiteHandle ) ){
//no need to add transfers, as the parent job and child
//job are run in the same directory on the pool
continue;
}
String sourceURI = null;
//PM-590 Stricter checks
/*
FileServer destSiteSharedScratchFS = destSite.selectHeadNodeScratchSharedFileServer( FileServer.OPERATION.put );
if( destSiteSharedScratchFS == null ){
this.complainForScratchFileServer( job, FileServer.OPERATION.put, destSiteHandle );
}
StringBuffer buffer = new StringBuffer();
buffer.append( destSiteSharedScratchFS.getURLPrefix() ).
append( mSiteStore.getExternalWorkDirectory(
destSiteSharedScratchFS,
destSiteHandle) );
String thirdPartyDestPutURI = buffer.toString();
*/
String thirdPartyDestPutURI = this.getURLOnSharedScratch( destSite, job, OPERATION.put, null );
//definite inconsitency as url prefix and mount point
//are not picked up from the same server
boolean localTransfer = runTransferOnLocalSite( destSiteHandle, thirdPartyDestPutURI, Job.INTER_POOL_JOB );
String destURI = localTransfer ?
//construct for third party transfer
thirdPartyDestPutURI :
//construct for normal transfer
"file://" + mSiteStore.getInternalWorkDirectory( destSiteHandle, destRemoteDir );
for (Iterator fileIt = pJob.getOutputFiles().iterator(); fileIt.hasNext(); ){
PegasusFile pf = (PegasusFile) fileIt.next();
String outFile = pf.getLFN();
if( job.getInputFiles().contains( pf ) ){
String sourceURL = null;
String destURL = destURI + File.separator + outFile;
String thirdPartyDestURL = thirdPartyDestPutURI + File.separator +
outFile;
FileTransfer ft = new FileTransfer(outFile,pJob.jobName);
ft.setSize( pf.getSize() );
ft.addDestination(destSiteHandle,destURL);
//for intersite transfers we need to track in transient rc
//for the cleanup algorithm
//only the destination is tracked as source will have been
//tracked for the parent jobs
trackInPlannerCache( outFile, thirdPartyDestURL, destSiteHandle );
//in the workflow cache we track the get URL for the outfile
String thirdPartyDestGetURL = this.getURLOnSharedScratch( destSite, job, OPERATION.get, outFile );
trackInWorkflowCache( outFile, thirdPartyDestGetURL, destSiteHandle );
//add all the possible source urls iterating through
//the list of grid ftp servers associated with the dest pool.
boolean first = true;
Directory parentScratchDir = mSiteStore.lookup( pJob.getStagingSiteHandle() ).getDirectory( Directory.TYPE.shared_scratch );
if( parentScratchDir == null ){
throw new RuntimeException( "Unable to determine the scratch dir for site " + pJob.getStagingSiteHandle() );
}
//retrive all the file servers matching the get operations
for( FileServer.OPERATION op : FileServer.OPERATION.operationsForGET() ){
for( Iterator it1 = parentScratchDir.getFileServersIterator(op); it1.hasNext(); ){
FileServer server = ( FileServer)it1.next();
//definite inconsitency as url prefix and mount point
//are not picked up from the same server
sourceURI = server.getURLPrefix();
//sourceURI += server.getMountPoint();
sourceURI += mSiteStore.getExternalWorkDirectory(server, pJob.getSiteHandle());
sourceURL = sourceURI + File.separator + outFile;
if(!(sourceURL.equalsIgnoreCase(thirdPartyDestURL))){
//add the source url only if it does not match to
//the third party destination url
ft.addSource(pJob.getStagingSiteHandle(), sourceURL);
}
first = false;
}
}
if( ft.isValid() ){
if( localTransfer ){
localTransfers.add(ft);
}
else{
remoteTransfers.add(ft);
}
}
}
}
}
result[0] = localTransfers;
result[1] = remoteTransfers;
return result;
}
/**
* Special Handling for a DAGJob for retrieving files from the Replica Catalog.
*
* @param job the DAGJob
* @param searchFiles file that need to be looked in the Replica Catalog.
*/
private void getFilesFromRC( DAGJob job, Collection searchFiles ){
//dax appears in adag element
String dag = null;
//go through all the job input files
//and set transfer flag to false
for (Iterator<PegasusFile> it = job.getInputFiles().iterator(); it.hasNext();) {
PegasusFile pf = it.next();
//at the moment dax files are not staged in.
//remove from input set of files
//part of the reason is about how to handle where
//to run the DAGJob. We dont have much control over it.
it.remove();
}
String lfn = job.getDAGLFN();
ReplicaLocation rl = mRCBridge.getFileLocs( lfn );
if (rl == null) { //flag an error
throw new RuntimeException(
"TransferEngine.java: Can't determine a location to " +
"transfer input file for DAG lfn " + lfn + " for job " +
job.getName());
}
ReplicaCatalogEntry selLoc = mReplicaSelector.selectReplica( rl,
job.getSiteHandle(),
true );
String pfn = selLoc.getPFN();
//some extra checks to ensure paths
if( pfn.startsWith( File.separator ) ){
dag = pfn;
}
else if( pfn.startsWith( PegasusURL.FILE_URL_SCHEME ) ){
// dag = Utility.getAbsolutePath( pfn );
dag = new PegasusURL( pfn ).getPath();
}
else{
throw new RuntimeException( "Invalid URL Specified for DAG Job " + job.getName() + " -> " + pfn );
}
job.setDAGFile(dag);
//set the directory if specified
job.setDirectory((String) job.dagmanVariables.removeKey(Dagman.DIRECTORY_EXTERNAL_KEY));
}
/**
* Special Handling for a DAXJob for retrieving files from the Replica Catalog.
*
* @param job the DAXJob
* @param searchFiles file that need to be looked in the Replica Catalog.
*/
private void getFilesFromRC( DAXJob job, Collection searchFiles ){
//dax appears in adag element
String dax = null;
//go through all the job input files
//and set transfer flag to false
for (Iterator<PegasusFile> it = job.getInputFiles().iterator(); it.hasNext();) {
PegasusFile pf = it.next();
//at the moment dax files are not staged in.
//remove from input set of files
//part of the reason is about how to handle where
//to run the DAGJob. We dont have much control over it.
it.remove();
}
String lfn = job.getDAXLFN();
ReplicaLocation rl = mRCBridge.getFileLocs( lfn );
if (rl == null) { //flag an error
throw new RuntimeException(
"TransferEngine.java: Can't determine a location to " +
"transfer input file for DAX lfn " + lfn + " for job " +
job.getName());
}
ReplicaCatalogEntry selLoc = mReplicaSelector.selectReplica( rl,
job.getSiteHandle(),
true );
String pfn = selLoc.getPFN();
//some extra checks to ensure paths
if( pfn.startsWith( File.separator ) ){
dax = pfn;
}
else if( pfn.startsWith( PegasusURL.FILE_URL_SCHEME ) ){
// dax = Utility.getAbsolutePath( pfn );
dax = new PegasusURL( pfn ).getPath();
}
else{
throw new RuntimeException( "Invalid URL Specified for DAX Job " + job.getName() + " -> " + pfn );
}
//add the dax to the argument
StringBuffer arguments = new StringBuffer();
arguments.append(job.getArguments()).
append(" --dax ").append(dax);
job.setArguments(arguments.toString());
}
/**
* It looks up the RCEngine Hashtable to lookup the locations for the
* files and add nodes to transfer them. If a file is not found to be in
* the Replica Catalog the Transfer Engine flags an error and exits
*
* @param job the <code>Job</code>object for whose ipfile have
* to search the Replica Mechanism for.
* @param searchFiles Vector containing the PegasusFile objects corresponding
* to the files that need to have their mapping looked
* up from the Replica Mechanism.
*/
private void getFilesFromRC( Job job, Collection searchFiles ) {
//Vector vFileTX = new Vector();
//Collection<FileTransfer> symLinkFileTransfers = new LinkedList();
Collection<FileTransfer> localFileTransfers = new LinkedList();
Collection<FileTransfer> remoteFileTransfers = new LinkedList();
String jobName = job.logicalName;
String stagingSiteHandle = job.getStagingSiteHandle();
//contains the remote_initialdir if specified for the job
String eRemoteDir = job.vdsNS.getStringValue(
Pegasus.REMOTE_INITIALDIR_KEY);
SiteCatalogEntry stagingSite = mSiteStore.lookup( stagingSiteHandle );
//we are using the pull mode for data transfer
String scheme = "file";
//sAbsPath would be just the source directory absolute path
//dAbsPath would be just the destination directory absolute path
/*
//PM-590 Stricter checks
FileServer stagingSiteSharedScratchFS = stagingSite.selectHeadNodeScratchSharedFileServer( FileServer.OPERATION.put );
if( stagingSiteSharedScratchFS == null ){
this.complainForScratchFileServer( job, FileServer.OPERATION.put, stagingSiteHandle);
}
String dAbsPath = mSiteStore.getExternalWorkDirectory( stagingSiteSharedScratchFS,
stagingSiteHandle);
String sAbsPath = null;
//sDirURL would be the url to the source directory.
//dDirPutURL would be the url to the destination directoy
//and is always a networked url.
String dDirPutURL = stagingSiteSharedScratchFS.getURLPrefix() + dAbsPath;
*/
//sDirURL would be the url to the source directory.
//dDirPutURL would be the url to the destination directoy
//and is always a networked url.
String dDirPutURL = this.getURLOnSharedScratch( stagingSite, job, OPERATION.put, null );
String dDirGetURL = this.getURLOnSharedScratch( stagingSite, job, OPERATION.get, null );
String sDirURL = null;
String sAbsPath = null;
String dAbsPath = mSiteStore.getInternalWorkDirectory( stagingSiteHandle, eRemoteDir );
//file dest dir is destination dir accessed as a file URL
String fileDestDir = scheme + "://" + dAbsPath;
//check if the execution pool is third party or not
boolean runTransferOnLocalSite = runTransferOnLocalSite( stagingSiteHandle, dDirPutURL, Job.STAGE_IN_JOB);
String destDir = ( runTransferOnLocalSite ) ?
//use the full networked url to the directory
dDirPutURL
:
//use the default pull mode
fileDestDir;
for( Iterator it = searchFiles.iterator(); it.hasNext(); ){
String sourceURL = null,destPutURL = null, destGetURL =null;
PegasusFile pf = (PegasusFile) it.next();
List pfns = null;
ReplicaLocation rl = null;
String lfn = pf.getLFN();
NameValue nv = null;
//see if the pf is infact an instance of FileTransfer
if( pf instanceof FileTransfer ){
//that means we should be having the source url already.
//nv contains both the source pool and the url.
//This happens in case of AI Planner or transfer of executables
nv = ((FileTransfer)pf).getSourceURL();
NameValue destNV = ((FileTransfer)pf).removeDestURL();
if( destNV == null ){
//the source URL was specified in the DAX
//no transfer of executables case
throw new RuntimeException( "Unreachable code . Signifies error in internal logic " );
}
else{
//staging of executables case
destPutURL = destNV.getValue();
destPutURL = (runTransferOnLocalSite( stagingSiteHandle, destPutURL, Job.STAGE_IN_JOB))?
//the destination URL is already third party
//enabled. use as it is
destPutURL:
//explicitly convert to file URL scheme
scheme + "://" + new PegasusURL( destPutURL ).getPath();
//for time being for this case the get url is same as put url
destGetURL = destPutURL;
}
}
else{
//query the replica services and get hold of pfn
rl = mRCBridge.getFileLocs( lfn );
pfns = (rl == null) ? null: rl.getPFNList();
}
if ( pfns == null && nv == null ) {
//check to see if the input file is optional
if(pf.fileOptional()){
//no need to add a transfer node for it if no location found
//remove the PegasusFile object from the list of
//input files for the job
boolean removed = job.getInputFiles().remove( pf );
//System.out.println( "Removed " + pf.getLFN() + " " + removed );
continue;
}
//flag an error
throw new RuntimeException(
"TransferEngine.java: Can't determine a location to " +
"transfer input file for lfn " + lfn + " for job " +
job.getName());
}
ReplicaCatalogEntry selLoc = (nv == null)?
//select from the various replicas
mReplicaSelector.selectReplica( rl,
job.getSiteHandle(),
runTransferOnLocalSite ):
//we have the replica already selected
new ReplicaCatalogEntry( nv.getValue(), nv.getKey() );
//check if we need to replace url prefix for
//symbolic linking
boolean symLinkSelectedLocation;
if ( symLinkSelectedLocation =
(mUseSymLinks && selLoc.getResourceHandle().equals( job.getStagingSiteHandle() )) ) {
//resolve any srm url's that are specified
selLoc = replaceSourceProtocolFromURL( selLoc );
}
//get the file to the job's execution pool
//this is assuming that there are no directory paths
//in the pfn!!!
sDirURL = selLoc.getPFN().substring( 0, selLoc.getPFN().lastIndexOf(File.separator) );
//try to get the directory absolute path
//yes i know that we sending the url to directory
//not the file.
sAbsPath = new PegasusURL( sDirURL ).getPath();
//the final source and destination url's to the file
sourceURL = selLoc.getPFN();
if( destPutURL == null ){
//no staging of executables case.
//we construct destination URL to file.
StringBuffer destPFN = new StringBuffer();
if( symLinkSelectedLocation ){
//we use the file URL location to dest dir
//in case we are symlinking
//destPFN.append( fileDestDir );
destPFN.append( this.replaceProtocolFromURL( destDir ) );
}
else{
//we use whatever destDir was set to earlier
destPFN.append( destDir );
}
destPFN.append( File.separator).append( lfn );
destPutURL = destPFN.toString();
destGetURL = dDirGetURL + File.separator + lfn;
}
//we have all the chopped up combos of the urls.
//do some funky matching on the basis of the fact
//that each pool has one shared filesystem
//match the source and dest 3rd party urls or
//match the directory url knowing that lfn and
//(source and dest pool) are same
try{
if(sourceURL.equalsIgnoreCase(dDirPutURL + File.separator + lfn)||
( selLoc.getResourceHandle().equalsIgnoreCase( stagingSiteHandle ) &&
lfn.equals( sourceURL.substring(sourceURL.lastIndexOf(File.separator) + 1)) &&
//sAbsPath.equals( dAbsPath )
new File( sAbsPath ).getCanonicalPath().equals( new File( dAbsPath).getCanonicalPath())
)
){
//do not need to add any transfer node
StringBuffer message = new StringBuffer( );
message.append( sAbsPath ).append( " same as " ).append( dAbsPath );
mLogger.log( message.toString() , LogManager.DEBUG_MESSAGE_LEVEL );
message = new StringBuffer();
message.append( " Not transferring ip file as ").append( lfn ).
append( " for job " ).append( job.jobName ).append( " to site " ).append( stagingSiteHandle );
mLogger.log( message.toString() , LogManager.DEBUG_MESSAGE_LEVEL );
continue;
}
}catch( IOException ioe ){
/*ignore */
}
//add locations of input data on the remote site to the transient RC
boolean bypassFirstLevelStaging = this.bypassStagingForInputFile( selLoc , pf , job.getSiteHandle() );
if( bypassFirstLevelStaging ){
//only the files for which we bypass first level staging , we
//store them in the planner cache as a GET URL and associate with the compute site
//PM-698
trackInPlannerCache( lfn, sourceURL, selLoc.getResourceHandle(), OPERATION.get );
trackInWorkflowCache( lfn, sourceURL, selLoc.getResourceHandle() );
//ensure the input file does not get cleaned up by the
//InPlace cleanup algorithm
pf.setForCleanup( false );
continue;
}
else{
//track the location where the data is staged as
//part of the first level staging
//we always store the thirdparty url
//trackInCaches( lfn, destPutURL, job.getSiteHandle() );
trackInPlannerCache( lfn,
destPutURL,
job.getStagingSiteHandle());
trackInWorkflowCache( lfn,
destGetURL,
job.getStagingSiteHandle());
}
//construct the file transfer object
FileTransfer ft = (pf instanceof FileTransfer) ?
(FileTransfer)pf:
new FileTransfer( lfn, jobName, pf.getFlags() );
//make sure the type information is set in file transfer
ft.setType( pf.getType() );
ft.setSize( pf.getSize() );
//the transfer mode for the file needs to be
//propogated for optional transfers.
ft.setTransferFlag(pf.getTransferFlag());
//to prevent duplicate source urls
if(ft.getSourceURL() == null){
ft.addSource( selLoc.getResourceHandle(), sourceURL);
}
//to prevent duplicate destination urls
if(ft.getDestURL() == null)
ft.addDestination(stagingSiteHandle,destPutURL);
if( symLinkSelectedLocation || !runTransferOnLocalSite ){
//all symlink transfers and user specified remote transfers
remoteFileTransfers.add(ft);
}
else{
localFileTransfers.add(ft);
}
//we need to set destPutURL to null
destPutURL = null;
}
//call addTransferNode
if (!localFileTransfers.isEmpty() || !remoteFileTransfers.isEmpty()) {
mTXRefiner.addStageInXFERNodes(job, localFileTransfers, remoteFileTransfers );
}
}
/**
* Replaces the SRM URL scheme from the url, and replaces it with the
* file url scheme and returns in a new object if replacement happens.
* The original object passed as a parameter still remains the same.
*
* @param rce the <code>ReplicaCatalogEntry</code> object whose url need to be
* replaced.
*
* @return the object with the url replaced.
*/
protected ReplicaCatalogEntry replaceSourceProtocolFromURL( ReplicaCatalogEntry rce ) {
String pfn = rce.getPFN();
//if the pfn starts with a file url we
//dont need to replace . a sanity check
if( pfn.startsWith( PegasusURL.FILE_URL_SCHEME ) ){
return rce;
}
/* special handling for SRM urls */
StringBuffer newPFN = new StringBuffer();
if( mSRMServiceURLToMountPointMap.containsKey( rce.getResourceHandle() ) ){
//try to do replacement of URL with internal mount point
NameValue nv = mSRMServiceURLToMountPointMap.get( rce.getResourceHandle() );
String urlPrefix = nv.getKey();
if( pfn.startsWith( urlPrefix ) ){
//replace the starting with the mount point
newPFN.append( PegasusURL.FILE_URL_SCHEME ).append( "//" );
newPFN.append( nv.getValue() );
newPFN.append( pfn.substring( urlPrefix.length(), pfn.length() ));
mLogger.log( "Replaced pfn " + pfn + " with " + newPFN.toString() ,
LogManager.TRACE_MESSAGE_LEVEL );
}
}
if( newPFN.length() == 0 ){
//there is no SRM Replacement to do
//Still do the FILE replacement
//return the original object
//we have to the manual replacement
/*
String hostName = Utility.getHostName( pfn );
newPFN.append( FILE_URL_SCHEME ).append( "//" );
//we want to skip out the hostname
newPFN.append( pfn.substring( pfn.indexOf( hostName ) + hostName.length() ) );
*/
newPFN.append( PegasusURL.FILE_URL_SCHEME ).append( "//" );
newPFN.append( new PegasusURL( pfn ).getPath() );
}
//we do not need a full clone, just the PFN
ReplicaCatalogEntry result = new ReplicaCatalogEntry( newPFN.toString(),
rce.getResourceHandle() );
for( Iterator it = rce.getAttributeIterator(); it.hasNext();){
String key = (String)it.next();
result.addAttribute( key, rce.getAttribute( key ) );
}
return result;
}
/**
* Replaces the gsiftp URL scheme from the url, and replaces it with the
* symlink url scheme and returns in a new object. The original object
* passed as a parameter still remains the same.
*
* @param pfn the pfn that needs to be replaced
*
* @return the replaced PFN
*/
protected String replaceProtocolFromURL( String pfn ) {
/* special handling for SRM urls */
StringBuffer newPFN = new StringBuffer();
if( pfn.startsWith(PegasusURL.FILE_URL_SCHEME) ){
//special handling for FILE URL's as
//utility hostname functions dont hold up
newPFN.append( PegasusURL.SYMLINK_URL_SCHEME ).
append( pfn.substring( PegasusURL.FILE_URL_SCHEME.length() ) );
//System.out.println( "Original PFN " + pfn + " \nReplaced PFN " + newPFN.toString() );
return newPFN.toString();
}
newPFN.append( PegasusURL.SYMLINK_URL_SCHEME ).append( "//" );
//we want to skip out the hostname
newPFN.append( new PegasusURL( pfn ).getPath() );
return newPFN.toString();
}
/**
* Constructs a Properties objects by parsing the relevant SRM
* pegasus properties.
*
* For example, if users have the following specified in properties file
* <pre>
* pegasus.transfer.srm.ligo-cit.service.url srm://osg-se.ligo.caltech.edu:10443/srm/v2/server?SFN=/mnt/hadoop
* pegasus.transfer.srm.ligo-cit.service.mountpoint /mnt/hadoop
* </pre>
*
* then, a Map is create the associates ligo-cit with NameValue object
* containing the service url and mount point ( ).
*
* @param props the <code>PegasusProperties</code> object
*
* @return Map that maps a site name to a NameValue object that has the
* URL prefix and the mount point
*/
private Map<String, NameValue> constructSiteToSRMServerMap( PegasusProperties props ) {
Map<String, NameValue> m = new HashMap();
//first strip of prefix from properties and get matching subset
Properties siteProps = props.matchingSubset( TransferEngine.SRM_PROPERTIES_PREFIX, false );
//retrieve all the sites for which SRM servers are specified
Map<String, String> m1 = new HashMap(); //associates site name to url prefix
Map<String, String> m2 = new HashMap(); //associates site name to mount point
for( Iterator it = siteProps.keySet().iterator(); it.hasNext(); ){
String key = (String) it.next();
//determine the site name
String site = key.substring( 0, key.indexOf( "." ) );
if( key.endsWith( TransferEngine.SRM_SERVICE_URL_PROPERTIES_SUFFIX ) ){
m1.put( site, siteProps.getProperty( key ) );
}
else if( key.endsWith( TransferEngine.SRM_MOUNT_POINT_PROPERTIES_SUFFIX ) ){
m2.put( site, siteProps.getProperty( key ) );
}
}
//now merge the information into m and return
for( Iterator <Map.Entry<String, String>>it = m1.entrySet().iterator(); it.hasNext(); ){
Map.Entry<String, String> entry = it.next();
String site = entry.getKey();
String url = entry.getValue();
String mountPoint = m2.get( site );
if( mountPoint == null ){
mLogger.log( "Mount Point for SRM server not specified in properties for site " + site,
LogManager.WARNING_MESSAGE_LEVEL );
continue;
}
m.put( site, new NameValue( url, mountPoint ) );
}
mLogger.log( "SRM Server map is " + m,
LogManager.DEBUG_MESSAGE_LEVEL );
return m;
}
/**
* It gets the output files for all the nodes which are specified in
* the nodes passed.
*
* @param nodes List<GraphNode> containing the jobs
*
*
* @return Set of PegasusFile objects
*/
private Set<PegasusFile> getOutputFiles( List<GraphNode> nodes ) {
Set<PegasusFile> files = new HashSet();
for( GraphNode n : nodes ){
Job job = (Job)n.getContent();
files.addAll( job.getOutputFiles() );
}
return files;
}
/**
* Initialize the Stageout Site Directory factory.
* The factory is used to returns the relative directory that a particular
* file needs to be staged to on the output site.
*
* @param workflow the workflow to which the transfer nodes need to be
* added.
*
*/
protected void initializeStageOutSiteDirectoryFactory( ADag workflow ){
String outputSite = mPOptions.getOutputSite();
boolean stageOut = (( outputSite != null ) && ( outputSite.trim().length() > 0 ));
if (!stageOut ){
//no initialization and return
mLogger.log( "No initialization of StageOut Site Directory Factory",
LogManager.DEBUG_MESSAGE_LEVEL );
return;
}
// create files in the directory, unless anything else is known.
SiteCatalogEntry entry = mSiteStore.lookup( outputSite );
if( entry == null ){
throw new RuntimeException( "Unable to lookup site catalog for site " + outputSite );
}
mStageoutDirectory = entry.getHeadNodeStorageDirectory();
if( mStageoutDirectory == null ){
throw new RuntimeException( "No Storage directory specified for site " + outputSite );
}
// mStageOutBaseDirectory = mSiteStore.getExternalStorageDirectory( outputSite );
String addOn = mSiteStore.getRelativeStorageDirectoryAddon( );
//all file factories intialized with the addon component only
if( this.mDeepStorageStructure ){
// create hashed, and levelled directories
try {
VirtualDecimalHashedFileFactory temp = null;
//get the total number of files that need to be stageout
int totalFiles = 0;
for ( Iterator it = workflow.jobIterator(); it.hasNext(); ){
Job job = ( Job )it.next();
//traverse through all the job output files
for( Iterator opIt = job.getOutputFiles().iterator(); opIt.hasNext(); ){
if( !((PegasusFile)opIt.next()).getTransientTransferFlag() ){
//means we have to stage to output site
totalFiles++;
}
}
}
// temp = new VirtualDecimalHashedFileFactory( mStageOutBaseDirectory, totalFiles );
temp = new VirtualDecimalHashedFileFactory( addOn, totalFiles );
//each stageout file has only 1 file associated with it
temp.setMultiplicator( 1 );
mFactory = temp;
}
catch (IOException e) {
//wrap into runtime and throw
throw new RuntimeException( "While initializing HashedFileFactory", e );
}
}
else{
try {
//Create a flat file factory
// mFactory = new VirtualFlatFileFactory( mStageOutBaseDirectory ); // minimum default
mFactory = new VirtualFlatFileFactory( addOn ); // minimum default
} catch ( IOException ioe ) {
throw new RuntimeException( "Unable to generate files in the submit directory " ,
ioe );
}
}
}
/**
* Tracks the files created by a job in the both the planner and workflow cache
* The planner cache stores the put URL's and the GET URL is stored in the
* workflow cache.
*
* @param job the job whose input files need to be tracked.
*/
private void trackInCaches( Job job ){
//check if there is a remote initialdir set
String path = job.vdsNS.getStringValue(
Pegasus.REMOTE_INITIALDIR_KEY );
SiteCatalogEntry stagingSiteEntry = mSiteStore.lookup( job.getStagingSiteHandle() );
if ( stagingSiteEntry == null ) {
this.poolNotFoundMsg( job.getStagingSiteHandle(), "vanilla" ) ;
mLogger.log( mLogMsg, LogManager.ERROR_MESSAGE_LEVEL );
throw new RuntimeException( mLogMsg );
}
for( Iterator it = job.getOutputFiles().iterator(); it.hasNext(); ){
PegasusFile pf = (PegasusFile) it.next();
String lfn = pf.getLFN();
//construct the URL to track in planner cache
String stagingSitePutURL = this.getURLOnSharedScratch( stagingSiteEntry, job, OPERATION.put, lfn);
trackInPlannerCache( lfn, stagingSitePutURL, stagingSiteEntry.getSiteHandle() );
String stagingSiteGetURL = this.getURLOnSharedScratch( stagingSiteEntry, job, OPERATION.get, lfn);
trackInWorkflowCache( lfn, stagingSiteGetURL, stagingSiteEntry.getSiteHandle() );
}
}
/**
* Inserts an entry into the planner cache as a put URL.
*
*
* @param lfn the logical name of the file.
* @param pfn the pfn
* @param site the site handle
*/
private void trackInPlannerCache( String lfn,
String pfn,
String site ){
trackInPlannerCache( lfn, pfn, site, OPERATION.put );
}
/**
* Inserts an entry into the planner cache as a put URL.
*
*
* @param lfn the logical name of the file.
* @param pfn the pfn
* @param site the site handle
* @param type the type of url
*/
private void trackInPlannerCache( String lfn,
String pfn,
String site,
OPERATION type ){
mPlannerCache.insert( lfn, pfn, site, type );
}
/**
* Inserts an entry into the workflow cache that is to be written out to the
* submit directory.
*
* @param lfn the logical name of the file.
* @param pfn the pfn
* @param site the site handle
*/
private void trackInWorkflowCache( String lfn,
String pfn,
String site ){
mWorkflowCache.insert( lfn, pfn, site );
}
/**
* Returns a URL on the shared scratch of the staging site
*
* @param entry the SiteCatalogEntry for the associated stagingsite
* @param job the job
* @param operation the FileServer operation for which we need the URL
* @param lfn the LFN can be null to get the path to the directory
*
* @return the URL
*/
private String getURLOnSharedScratch( SiteCatalogEntry entry ,
Job job,
FileServer.OPERATION operation ,
String lfn ){
StringBuffer url = new StringBuffer();
FileServer getServer = entry.selectHeadNodeScratchSharedFileServer( operation );
if( getServer == null ){
this.complainForScratchFileServer(job, operation, entry.getSiteHandle());
}
url.append( getServer.getURLPrefix() ).
append( mSiteStore.getExternalWorkDirectory(getServer, entry.getSiteHandle() ));
if( lfn != null ){
url.append( File.separatorChar ).append( lfn );
}
return url.toString();
}
/**
* Returns the full path on remote output site, where the lfn will reside.
* Each call to this function could trigger a change in the directory
* returned depending upon the file factory being used.
*
* @param directory the directory on the output site
* @param operation the get or put operation
* @param lfn the lfn
*
* @return the URL as a String
*/
private String getURLOnStageoutSite(Directory directory, OPERATION operation, String lfn) {
//PM-590 stricter checks
FileServer server = directory.selectFileServer( operation );
// String urlPrefix = p.selectHeadNodeScratchSharedFileServerURLPrefix( FileServer.OPERATION.put );
if( server == null ){
this.complainForStorageFileServer( "", operation, this.mPlannerOptions.getOutputSite() );
}
return this.getURLOnStageoutSite( server, lfn );
}
/**
* Returns the full path on remote output site, where the lfn will reside.
* Each call to this function could trigger a change in the directory
* returned depending upon the file factory being used.
*
* @param server the file server to use
* @param lfn the logical filename of the file.
*
* @return the storage mount point.
*/
private String getURLOnStageoutSite( FileServer server, String lfn ){
StringBuffer url = new StringBuffer( server.getURL() );
try{
//the factory will give us the relative
//add on part
String addOn = mFactory.createFile( lfn ).toString();
//check if we need to add file separator
//do we really need it?
if( addOn.indexOf( File.separator ) != 0 ){
url.append( File.separator );
}
url.append( addOn );
}
catch( IOException e ){
throw new RuntimeException( "IOException " , e );
}
return url.toString();
}
/**
* Complains for a missing head node storage file server on a site for a job
*
* @param job the job
* @param operation the operation
* @param site the site
*/
private void complainForStorageFileServer( Job job,
FileServer.OPERATION operation,
String site) {
this.complainForScratchFileServer( job.getID(), operation, site);
}
/**
* Complains for a missing head node storage file server on a site for a job
*
* @param jobname the name of the job
* @param operation the file server operation
* @param site the site
*/
private void complainForStorageFileServer( String jobname,
FileServer.OPERATION operation,
String site) {
StringBuffer error = new StringBuffer();
error.append( "[" ).append( REFINER_NAME ).append( "] ");
if( jobname != null ){
error.append( "For job (" ).append( jobname).append( ")." );
}
error.append( " File Server not specified for shared-scratch filesystem for site: ").
append( site );
throw new RuntimeException( error.toString() );
}
/**
* Complains for a missing head node file server on a site for a job
*
* @param job the job
* @param operation the operation
* @param site the site
*/
private void complainForScratchFileServer( Job job,
FileServer.OPERATION operation,
String site) {
this.complainForScratchFileServer( job.getID(), operation, site);
}
/**
* Complains for a missing head node file server on a site for a job
*
* @param jobname the name of the job
* @param operation the file server operation
* @param site the site
*/
private void complainForScratchFileServer( String jobname,
FileServer.OPERATION operation,
String site) {
StringBuffer error = new StringBuffer();
error.append( "[" ).append( REFINER_NAME ).append( "] ");
if( jobname != null ){
error.append( "For job (" ).append( jobname).append( ")." );
}
error.append( " File Server not specified for shared-scratch filesystem for site: ").
append( site );
throw new RuntimeException( error.toString() );
}
/**
* Initializes a Replica Catalog Instance that is used to store
* the GET URL's for all files on the staging site ( inputs staged and outputs
* created ).
*
* @param dag the workflow being planned
*
* @return handle to transient catalog
*/
private ReplicaCatalog initializeWorkflowCacheFile( ADag dag ){
ReplicaCatalog rc = null;
mLogger.log("Initialising Workflow Cache File in the Submit Directory",
LogManager.DEBUG_MESSAGE_LEVEL );
Properties cacheProps = mProps.getVDSProperties().matchingSubset(
ReplicaCatalog.c_prefix,
false );
String file = mPOptions.getSubmitDirectory() + File.separatorChar +
getCacheFileName( dag );
//set the appropriate property to designate path to file
cacheProps.setProperty( WORKFLOW_CACHE_REPLICA_CATALOG_KEY, file );
try{
rc = ReplicaFactory.loadInstance(
WORKFLOW_CACHE_FILE_IMPLEMENTOR,
cacheProps);
}
catch( Exception e ){
throw new RuntimeException( "Unable to initialize Workflow Cache File in the Submit Directory " + file,
e );
}
return rc;
}
/**
* Constructs the basename to the cache file that is to be used
* to log the transient files. The basename is dependant on whether the
* basename prefix has been specified at runtime or not.
*
* @param adag the ADag object containing the workflow that is being
* concretized.
*
* @return the name of the cache file
*/
private String getCacheFileName(ADag adag){
StringBuffer sb = new StringBuffer();
String bprefix = mPOptions.getBasenamePrefix();
if(bprefix != null){
//the prefix is not null using it
sb.append(bprefix);
}
else{
//generate the prefix from the name of the dag
sb.append(adag.dagInfo.nameOfADag).append("-").
append(adag.dagInfo.index);
}
//append the suffix
sb.append(".cache");
return sb.toString();
}
/**
* Returns a boolean indicating whether to bypass first level staging for a
* file or not
*
* @param entry a ReplicaCatalogEntry matching the selected replica location.
* @param file the corresponding Pegasus File object
* @param computeSite the compute site where the associated job will run.
* @param isExecutable whether the file transferred is an executable file or not
*
* @return boolean indicating whether we need to enable bypass or not
*/
private boolean bypassStagingForInputFile( ReplicaCatalogEntry entry , PegasusFile file, String computeSite ) {
boolean bypass = false;
//check if user has it configured for bypassing the staging and
//we are in pegasus lite mode
if( this.mBypassStagingForInputs && mWorkerNodeExecution ){
boolean isFileURL = entry.getPFN().startsWith( PegasusURL.FILE_URL_SCHEME);
String fileSite = entry.getResourceHandle();
if( this.mSetupForCondorIO ){
//additional check for condor io
//we need to inspect the URL and it's location
//only file urls for input files are eligible for bypass
if( isFileURL &&
fileSite.equals( "local" ) ){
//in condor io we cannot remap the destination URL
//we need to make sure the PFN ends with lfn to enable bypass
bypass = entry.getPFN().endsWith( file.getLFN() );
}
}
else{
//for non shared fs case we can bypass all url's safely
//other than file urls
bypass = isFileURL ?
fileSite.equalsIgnoreCase( computeSite )://file site is same as the compute site
true;
}
}
return bypass;
}
}
| src/edu/isi/pegasus/planner/refiner/TransferEngine.java | /**
* Copyright 2007-2008 University Of Southern California
*
* 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 edu.isi.pegasus.planner.refiner;
import edu.isi.pegasus.planner.catalog.site.classes.FileServer;
import edu.isi.pegasus.planner.catalog.site.classes.SiteCatalogEntry;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.planner.classes.ADag;
import edu.isi.pegasus.planner.classes.FileTransfer;
import edu.isi.pegasus.planner.classes.NameValue;
import edu.isi.pegasus.planner.classes.PegasusFile;
import edu.isi.pegasus.planner.classes.ReplicaLocation;
import edu.isi.pegasus.planner.classes.Job;
import edu.isi.pegasus.planner.classes.PegasusBag;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.planner.namespace.Pegasus;
import edu.isi.pegasus.planner.partitioner.graph.GraphNode;
import edu.isi.pegasus.planner.partitioner.graph.Graph;
import edu.isi.pegasus.planner.partitioner.graph.Adapter;
import edu.isi.pegasus.planner.selector.ReplicaSelector;
import edu.isi.pegasus.planner.selector.replica.ReplicaSelectorFactory;
import edu.isi.pegasus.planner.transfer.Refiner;
import edu.isi.pegasus.planner.transfer.refiner.RefinerFactory;
import edu.isi.pegasus.planner.catalog.ReplicaCatalog;
import edu.isi.pegasus.planner.catalog.replica.ReplicaCatalogEntry;
import edu.isi.pegasus.common.util.FactoryException;
import edu.isi.pegasus.common.util.PegasusURL;
import edu.isi.pegasus.planner.catalog.replica.ReplicaFactory;
import edu.isi.pegasus.planner.catalog.site.classes.Directory;
import edu.isi.pegasus.planner.catalog.site.classes.FileServerType.OPERATION;
import edu.isi.pegasus.planner.classes.DAGJob;
import edu.isi.pegasus.planner.classes.DAXJob;
import edu.isi.pegasus.planner.classes.PlannerCache;
import edu.isi.pegasus.planner.classes.PlannerOptions;
import edu.isi.pegasus.planner.common.PegasusConfiguration;
import edu.isi.pegasus.planner.namespace.Dagman;
import org.griphyn.vdl.euryale.FileFactory;
import org.griphyn.vdl.euryale.VirtualDecimalHashedFileFactory;
import org.griphyn.vdl.euryale.VirtualFlatFileFactory;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.Properties;
/**
* The transfer engine, which on the basis of the pools on which the jobs are to
* run, adds nodes to transfer the data products.
*
* @author Karan Vahi
* @author Gaurang Mehta
* @version $Revision$
*
*/
public class TransferEngine extends Engine {
/**
* The MAX level is assigned as the level for deleted jobs.
* We can put it to Integer.MAX_VALUE, but it is rare that number of levels
* in a workflows exceed 1000.
*/
public static final int DELETED_JOBS_LEVEL = 1000;
/**
* The name of the Replica Catalog Implementer that is used to write out
* the workflow cache file in the submit directory.
*/
public static final String WORKFLOW_CACHE_FILE_IMPLEMENTOR = "FlushedCache";
/**
* The name of the source key for Replica Catalog Implementer that serves as
* cache
*/
public static final String WORKFLOW_CACHE_REPLICA_CATALOG_KEY = "file";
/**
* The property prefix for retrieving SRM properties.
*/
public static final String SRM_PROPERTIES_PREFIX = "pegasus.transfer.srm";
/**
* The suffix to retrive the service url for SRM server.
*/
public static final String SRM_SERVICE_URL_PROPERTIES_SUFFIX = "service.url";
/**
* The suffix to retrive the mount point for SRM server.
*/
public static final String SRM_MOUNT_POINT_PROPERTIES_SUFFIX = "mountpoint";
/**
* The name of the refiner for purposes of error logging
*/
public static final String REFINER_NAME = "TranferEngine";
/**
* A map that associates the site name with the SRM server url and mount point.
*/
private Map<String, NameValue> mSRMServiceURLToMountPointMap;
/**
* The DAG object to which the transfer nodes are to be added. This is the
* reduced Dag, which is got from the Reduction Engine.
*/
private ADag mDag;
/**
* The bridge to the Replica Catalog.
*/
private ReplicaCatalogBridge mRCBridge;
/**
* The handle to the replica selector that is to used to select the various
* replicas.
*/
private ReplicaSelector mReplicaSelector;
/**
* The handle to the transfer refiner that adds the transfer nodes into the
* workflow.
*/
private Refiner mTXRefiner;
/**
* Holds all the jobs deleted by the reduction algorithm.
*/
private List mDeletedJobs;
/**
* A SimpleFile Replica Catalog, that tracks all the files that are being
* materialized as part of workflow executaion.
*/
private PlannerCache mPlannerCache;
/**
* A Replica Catalog, that tracks all the GET URL's for the files on the
* staging sites.
*/
private ReplicaCatalog mWorkflowCache;
/**
* The handle to the file factory, that is used to create the top level
* directories for each of the partitions.
*/
private FileFactory mFactory;
/**
* The Directory on the output site as retrieved from the site catalog.
*/
private Directory mStageoutDirectory;
/**
* The working directory relative to the mount point of the execution pool.
* It is populated from the pegasus.dir.exec property from the properties file.
* If not specified then it work_dir is supposed to be the exec mount point
* of the execution pool.
*/
protected String mWorkDir;
/**
* A boolean indicating whether to have a deep directory structure for
* the storage directory or not.
*/
protected boolean mDeepStorageStructure;
/**
* This member variable if set causes the destination URL for the symlink jobs
* to have symlink:// url if the pool attributed associated with the pfn
* is same as a particular jobs execution pool.
*/
protected boolean mUseSymLinks;
/**
* A boolean indicating whether we are doing worker node execution or not.
*/
private boolean mWorkerNodeExecution;
/**
* The planner options passed to the planner
*/
private PlannerOptions mPlannerOptions;
/**
* A boolean indicating whether to bypass first level staging for inputs
*/
private boolean mBypassStagingForInputs;
/**
* A boolean to track whether condor file io is used for the workflow or not.
*/
private final boolean mSetupForCondorIO;
/**
* Overloaded constructor.
*
* @param reducedDag the reduced workflow.
* @param bag bag of initialization objects
* @param deletedJobs list of all jobs deleted by reduction algorithm.
* @param deletedLeafJobs list of deleted leaf jobs by reduction algorithm.
*/
public TransferEngine( ADag reducedDag,
PegasusBag bag,
List<Job> deletedJobs ,
List<Job> deletedLeafJobs){
super( bag );
mPlannerOptions = bag.getPlannerOptions();
mDeepStorageStructure = mProps.useDeepStorageDirectoryStructure();
mUseSymLinks = mProps.getUseOfSymbolicLinks();
mSRMServiceURLToMountPointMap = constructSiteToSRMServerMap( mProps );
mDag = reducedDag;
mDeletedJobs = deletedJobs;
mWorkerNodeExecution = mProps.executeOnWorkerNode();
mSetupForCondorIO = new PegasusConfiguration( mLogger).setupForCondorIO( mProps );
mBypassStagingForInputs = mProps.bypassFirstLevelStagingForInputs();
try{
mTXRefiner = RefinerFactory.loadInstance( reducedDag,
bag );
mReplicaSelector = ReplicaSelectorFactory.loadInstance(mProps);
}
catch(Exception e){
//wrap all the exceptions into a factory exception
throw new FactoryException("Transfer Engine ", e);
}
this.initializeStageOutSiteDirectoryFactory( reducedDag );
mWorkflowCache = this.initializeWorkflowCacheFile( reducedDag );
//log some configuration messages
mLogger.log("Transfer Refiner loaded is [" + mTXRefiner.getDescription() +
"]",LogManager.CONFIG_MESSAGE_LEVEL);
mLogger.log("ReplicaSelector loaded is [" + mReplicaSelector.description() +
"]",LogManager.CONFIG_MESSAGE_LEVEL);
}
/**
* Returns whether to run a transfer job on local site or not.
*
*
* @param site the site handle associated with the destination URL.
* @param destPutURL the destination URL
* @param type the type of transfer job for which the URL is being constructed.
*
* @return true indicating if the associated transfer job should run on local
* site or not.
*/
public boolean runTransferOnLocalSite( String site, String destinationURL, int type) {
//check if user has specified any preference in config
boolean result = true;
//short cut for local site
if( site.equals( "local" ) ){
//transfer to run on local site
return result;
}
if( mTXRefiner.refinerPreferenceForTransferJobLocation() ){
//refiner is advertising a preference for where transfer job
//should be run. Use that.
return mTXRefiner.refinerPreferenceForLocalTransferJobs( type );
}
if( mTXRefiner.runTransferRemotely( site, type )){
//always use user preference
return !result;
}
//check to see if destination URL is a file url
else if( destinationURL != null && destinationURL.startsWith( PegasusURL.FILE_URL_SCHEME ) ){
result = false;
}
return result;
}
/**
* Adds the transfer nodes to the workflow.
*
* @param rcb the bridge to the ReplicaCatalog.
* @param plannerCache an instance of the replica catalog that will
* store the locations of the files on the remote
* sites.
*/
public void addTransferNodes( ReplicaCatalogBridge rcb, PlannerCache plannerCache ) {
mRCBridge = rcb;
mPlannerCache = plannerCache;
Job currentJob;
String currentJobName;
Vector vOutPoolTX;
String msg;
String outputSite = mPOptions.getOutputSite();
//convert the dax to a graph representation and walk it
//in a top down manner
Graph workflow = Adapter.convert( mDag );
//go through each job in turn
boolean stageOut = (( outputSite != null ) && ( outputSite.trim().length() > 0 ));
for( Iterator it = workflow.iterator(); it.hasNext(); ){
GraphNode node = ( GraphNode )it.next();
currentJob = (Job)node.getContent();
//set the staging site for the job
//currentJob.setStagingSiteHandle( getStagingSite( currentJob ) );
//set the node depth as the level
currentJob.setLevel( node.getDepth() );
currentJobName = currentJob.getName();
mLogger.log("",LogManager.DEBUG_MESSAGE_LEVEL);
msg = "Job being traversed is " + currentJobName;
mLogger.log(msg, LogManager.DEBUG_MESSAGE_LEVEL);
msg = "To be run at " + currentJob.executionPool;
mLogger.log(msg, LogManager.DEBUG_MESSAGE_LEVEL);
//getting the parents of that node
List<GraphNode> parents = node.getParents();
mLogger.log("Parents of job:" + node.parentsToString(),
LogManager.DEBUG_MESSAGE_LEVEL);
processParents(currentJob, parents);
//transfer the nodes output files
//to the output pool
if ( stageOut ) {
SiteCatalogEntry stagingSite = mSiteStore.lookup( currentJob.getStagingSiteHandle() );
if (stagingSite == null ) {
mLogMsg = this.poolNotFoundMsg( currentJob.getSiteHandle(), "vanilla");
mLogger.log( mLogMsg, LogManager.ERROR_MESSAGE_LEVEL );
throw new RuntimeException( mLogMsg );
}
//PM-590 Stricter checks
String stagingSiteURLPrefix = stagingSite.selectHeadNodeScratchSharedFileServerURLPrefix( FileServer.OPERATION.put );
if( stagingSiteURLPrefix == null ){
this.complainForHeadNodeURLPrefix( REFINER_NAME, stagingSite.getSiteHandle(), FileServer.OPERATION.put, currentJob );
}
boolean localTransfer = runTransferOnLocalSite(
currentJob.getSiteHandle(),
stagingSiteURLPrefix,
Job.STAGE_OUT_JOB);
vOutPoolTX = getFileTX(outputSite, currentJob, localTransfer );
mTXRefiner.addStageOutXFERNodes( currentJob, vOutPoolTX, rcb, localTransfer );
}
else{
//create the cache file always
//Pegasus Bug PM-32 and PM-356
trackInCaches( currentJob );
}
}
//we are done with the traversal.
//mTXRefiner.done();
//get the deleted leaf jobs o/p files to output pool
//only if output pool is specified
//should be moved upwards in the pool. redundancy at present
if (outputSite != null &&
outputSite.trim().length() > 0
&& !mDeletedJobs.isEmpty() ) {
mLogger.log( "Adding stage out jobs for jobs deleted from the workflow", LogManager.INFO_MESSAGE_LEVEL );
for( Iterator it = this.mDeletedJobs.iterator(); it.hasNext() ;) {
currentJob = (Job)it.next();
currentJob.setLevel( TransferEngine.DELETED_JOBS_LEVEL );
//for a deleted node, to transfer it's output
//the execution pool should be set to local i.e submit host
currentJob.setSiteHandle( "local" );
//set the staging site for the deleted job
currentJob.setStagingSiteHandle( getStagingSite( currentJob ) );
//for jobs deleted during data reuse we dont
//go through the staging site. they are transferred
//directly to the output site.
vOutPoolTX = getDeletedFileTX(outputSite, currentJob);
if( !vOutPoolTX.isEmpty() ){
//the job is deleted anyways. The files exist somewhere
//as mentioned in the Replica Catalog. We assume it is
//URL remotely accessible
boolean localTransfer = true;
mTXRefiner.addStageOutXFERNodes( currentJob, vOutPoolTX, rcb, localTransfer, true );
}
}
}
//we are done with the traversal.
mTXRefiner.done();
//close the handle to the workflow cache file if it is written
//not the planner cache file
this.mWorkflowCache.close();
}
/**
* Returns the staging site to be used for a job. If a staging site is not
* determined from the options it is set to be the execution site for the job
*
* @param job the job for which to determine the staging site
*
* @return the staging site
*/
public String getStagingSite( Job job ){
String ss = this.mPOptions.getStagingSite( job.getSiteHandle() );
return (ss == null) ? job.getSiteHandle(): ss;
}
/**
* This gets the file transfer objects corresponding to the location of files
* found in the replica mechanism, and transfers it to the output pool asked
* by the user. If the output pool path and the one returned by the replica
* mechanism match then that object is not transferred.
*
* @param pool this the output pool which the user specifies at runtime.
* @param job The Job object corresponding to the leaf job which was
* deleted by the Reduction algorithm
*
* @return Vector of <code>FileTransfer</code> objects
*/
private Vector getDeletedFileTX( String pool, Job job ) {
Vector vFileTX = new Vector();
for( Iterator it = job.getOutputFiles().iterator(); it.hasNext(); ){
PegasusFile pf = (PegasusFile)it.next();
String lfn = pf.getLFN();
//we only have to get a deleted file that user wants to be transferred
if( pf.getTransientTransferFlag() ){
continue;
}
ReplicaLocation rl = mRCBridge.getFileLocs( lfn );
//sanity check
if( rl == null ){
throw new RuntimeException( "Unable to find a location in the Replica Catalog for output file " + lfn );
}
String putDestURL = getURLOnStageoutSite( mStageoutDirectory, FileServer.OPERATION.put, lfn );
String getDestURL = getURLOnStageoutSite( mStageoutDirectory, FileServer.OPERATION.get, lfn );
//selLocs are all the locations found in ReplicaMechanism corr
//to the pool pool
ReplicaLocation selLocs = mReplicaSelector.selectReplicas( rl,
pool,
this.runTransferOnLocalSite( pool,putDestURL, Job.STAGE_OUT_JOB ));
boolean flag = false;
FileTransfer ft = null;
//checking through all the pfn's returned on the pool
for ( Iterator selIt = selLocs.pfnIterator(); selIt.hasNext(); ) {
ReplicaCatalogEntry selLoc = ( ReplicaCatalogEntry ) selIt.next();
String sourceURL = selLoc.getPFN();
//check if the URL's match
if (sourceURL.trim().equalsIgnoreCase(putDestURL.trim())){
String msg = "The leaf file " + lfn +
" is already at the output pool " + pool;
mLogger.log(msg,LogManager.INFO_MESSAGE_LEVEL);
flag = true;
break;
}
ft = new FileTransfer( lfn, job.getName() );
ft.addSource( selLoc.getResourceHandle() , sourceURL );
ft.addDestination( pool, putDestURL );
ft.setURLForRegistrationOnDestination( getDestURL );
ft.setSize( pf.getSize() );
//System.out.println("Deleted Leaf Job File transfer object " + ft);
}
if (!flag) { // adding the last pfn
vFileTX.addElement(ft);
}
}
return vFileTX;
}
/**
* It processes a nodes parents and determines if nodes are to be added
* or not. All the input files for the job are searched in the output files of
* the parent nodes and the Replica Mechanism.
*
* @param job the <code>Job</code> object containing all the
* details of the job.
* @param parents list <code>GraphNode</code> ojbects corresponding to the parent jobs
* of the job.
*/
private void processParents(Job job, List<GraphNode> parents) {
Set nodeIpFiles = job.getInputFiles();
Vector vRCSearchFiles = new Vector(); //vector of PegasusFile
//getAll the output Files of the parents
Set<PegasusFile> parentsOutFiles = getOutputFiles( parents );
//interpool transfer of the nodes parents
//output files
Collection[] interSiteFileTX = this.getInterpoolFileTX(job, parents);
Collection localInterSiteTX = interSiteFileTX[0];
Collection remoteInterSiteTX = interSiteFileTX[1];
//only add if there are files to transfer
if( !localInterSiteTX.isEmpty()){
mTXRefiner.addInterSiteTXNodes(job, localInterSiteTX, true );
}
if( !remoteInterSiteTX.isEmpty() ){
mTXRefiner.addInterSiteTXNodes(job, remoteInterSiteTX, false );
}
//check if node ip files are in the parents out files
//if files are not, then these are to be got
//from the RC based on the transiency characteristic
for( Iterator it = nodeIpFiles.iterator(); it.hasNext(); ){
PegasusFile pf = (PegasusFile) it.next();
if( !parentsOutFiles.contains( pf ) ){
if (!pf.getTransientTransferFlag()) {
vRCSearchFiles.addElement(pf);
}
}
}
if (!vRCSearchFiles.isEmpty()) {
if( job instanceof DAXJob ){
getFilesFromRC( (DAXJob)job, vRCSearchFiles);
}
else if( job instanceof DAGJob ){
getFilesFromRC( (DAGJob)job, vRCSearchFiles);
}
else{
//get the locations from the RC
getFilesFromRC(job, vRCSearchFiles);
}
}
}
/**
* This gets the Vector of FileTransfer objects for the files which have to
* be transferred to an one destination pool. It checks for the transient
* flags for files. If the transfer transient flag is set, it means the file
* does not have to be transferred to the destination pool.
*
* @param destSiteHandle The pool to which the files are to be transferred to.
* @param job The <code>Job</code>object of the job whose output files
* are needed at the destination pool.
* @param localTransfer boolean indicating that associated transfer job will run
* on local site.
*
* @return Vector of <code>FileTransfer</code> objects
*/
private Vector getFileTX(String destPool, Job job, boolean localTransfer ) {
Vector vFileTX = new Vector();
//check if there is a remote initialdir set
String path = job.vdsNS.getStringValue(
Pegasus.REMOTE_INITIALDIR_KEY );
for( Iterator it = job.getOutputFiles().iterator(); it.hasNext(); ){
PegasusFile pf = (PegasusFile) it.next();
String file = pf.getLFN();
FileTransfer ft = this.constructFileTX( pf,
job,
destPool,
path,
localTransfer );
if (ft != null) {
vFileTX.add(ft);
}
}
return vFileTX;
}
/**
* Constructs the FileTransfer object on the basis of the transiency
* information. If the transient flag for transfer is set, the destPutURL for the
* FileTransfer object would be the execution directory, as this is the entry
* that has to be registered in the ReplicaMechanism
*
* @param pf the PegasusFile for which the transfer has to be done.
* @param stagingSiteHandle the staging site at which file is placed after execution.
* @param destSiteHandle the output pool where the job should be transferred
* @param job the name of the associated job.
* @param path the path that a user specifies in the profile for key
* remote_initialdir that results in the workdir being
* changed for a job on a execution pool.
* @param localTransfer boolean indicating that associated transfer job will run
* on local site.
*
* @return the corresponding FileTransfer object
*/
private FileTransfer constructFileTX( PegasusFile pf,
Job job,
String destSiteHandle,
String path,
boolean localTransfer ) {
String stagingSiteHandle = job.getStagingSiteHandle();
String lfn = pf.getLFN();
FileTransfer ft = null;
SiteCatalogEntry stagingSite = mSiteStore.lookup( stagingSiteHandle );
SiteCatalogEntry destinationSite = mSiteStore.lookup( destSiteHandle );
if (stagingSite == null || destinationSite == null) {
mLogMsg = (stagingSite == null) ?
this.poolNotFoundMsg(stagingSiteHandle, "vanilla") :
this.poolNotFoundMsg(destSiteHandle, "vanilla");
mLogger.log( mLogMsg, LogManager.ERROR_MESSAGE_LEVEL );
throw new RuntimeException( mLogMsg );
}
//the get
String sharedScratchGetURL = this.getURLOnSharedScratch( stagingSite, job, OPERATION.get, lfn );
String sharedScratchPutURL = this.getURLOnSharedScratch( stagingSite, job, OPERATION.put, lfn );
/*
FileServer stagingSiteSharedScratchFS = stagingSite.selectHeadNodeScratchSharedFileServer( FileServer.OPERATION.put );
if( stagingSiteSharedScratchFS == null ){
this.complainForScratchFileServer( job, FileServer.OPERATION.put, stagingSiteHandle );
}
StringBuffer buffer = new StringBuffer();
buffer.append( stagingSiteSharedScratchFS.getURLPrefix() ).
append( mSiteStore.getExternalWorkDirectory(stagingSiteSharedScratchFS, stagingSiteHandle)).
append( File.separatorChar ).append( lfn );
String sharedScratchGetURL = buffer.toString();
*/
//in the planner cache we track the output files put url on staging site
trackInPlannerCache( lfn, sharedScratchPutURL, stagingSiteHandle );
//in the workflow cache we track the output files put url on staging site
trackInWorkflowCache( lfn, sharedScratchGetURL, stagingSiteHandle );
//if both transfer and registration
//are transient return null
if (pf.getTransientRegFlag() && pf.getTransientTransferFlag()) {
return null;
}
//if only transient transfer flag
//means destPutURL and sourceURL
//are same and are equal to
//execution directory on stagingSiteHandle
if (pf.getTransientTransferFlag()) {
ft = new FileTransfer(lfn,job.getID(),pf.getFlags());
//set the transfer mode
ft.setSize( pf.getSize() );
ft.setTransferFlag(pf.getTransferFlag());
ft.addSource(stagingSiteHandle,sharedScratchGetURL);
ft.addDestination(stagingSiteHandle,sharedScratchGetURL);
ft.setURLForRegistrationOnDestination( sharedScratchGetURL );
}
//the source dir is the exec dir
//on exec pool and dest dir
//would be on the output pool
else {
//construct the source url depending on whether third party tx
String sourceURL = localTransfer ?
sharedScratchGetURL :
"file://" + mSiteStore.getInternalWorkDirectory(stagingSiteHandle,path) +
File.separator + lfn;
ft = new FileTransfer(lfn, job.getID(), pf.getFlags());
ft.setSize( pf.getSize() );
//set the transfer mode
ft.setTransferFlag(pf.getTransferFlag());
ft.addSource(stagingSiteHandle,sourceURL);
//if the PegasusFile is already an instance of
//FileTransfer the user has specified the destination
//that they want to use in the DAX 3.0
if( pf instanceof FileTransfer ){
//not really supported in DAX 3.3?
ft.addDestination( ((FileTransfer)pf).removeDestURL() );
return ft;
}
//add all the possible destination urls iterating through
//the list of grid ftp servers associated with the dest pool.
// Iterator it = mSiteStore.lookup( destSiteHandle ).getHeadNodeFS().getStorage().getSharedDirectory().getFileServersIterator();
Directory storageDirectory = mSiteStore.lookup( destSiteHandle ).getHeadNodeStorageDirectory();
if( storageDirectory == null ){
throw new RuntimeException( "No Storage directory specified for site " + destSiteHandle );
}
//sanity check
if( !storageDirectory.hasFileServerForPUTOperations() ){
//no file servers for put operations
throw new RuntimeException( " No File Servers specified for PUT Operation on Shared Storage on Headnode for site " + destSiteHandle );
}
for( FileServer.OPERATION op : FileServer.OPERATION.operationsForPUT() ){
for( Iterator it = storageDirectory.getFileServersIterator(op); it.hasNext();){
FileServer fs = (FileServer)it.next();
//file server on output site
String destURL = this.getURLOnStageoutSite( fs, lfn);
//if the paths match of dest URI
//and execDirURL we return null
if (sharedScratchGetURL.equalsIgnoreCase(destURL)) {
/*ft = new FileTransfer(file, job);
ft.addSource(stagingSiteHandle, sharedScratchGetURL);*/
ft.addDestination(stagingSiteHandle, sharedScratchGetURL);
ft.setURLForRegistrationOnDestination( sharedScratchGetURL );
//make the transfer transient?
ft.setTransferFlag(PegasusFile.TRANSFER_NOT);
return ft;
}
ft.addDestination( destSiteHandle, destURL );
}
}//end of different put operations
//construct a registration URL
ft.setURLForRegistrationOnDestination( constructRegistrationURL( storageDirectory ,destSiteHandle, lfn ) );
}
return ft;
}
/**
* Constructs a Registration URL for a LFN
*
* @param directory the storage directory
* @param site the site handle
* @param lfn the LFN for which the URL needs to be constructed
*
* @return the URL
*/
private String constructRegistrationURL( Directory directory , String site, String lfn ){
//sanity check
if( !directory.hasFileServerForGETOperations() ){
//no file servers for GET operations
throw new RuntimeException( " No File Servers specified for GET Operation on Shared Storage for site " + site );
}
String url = null;
for( FileServer.OPERATION op : FileServer.OPERATION.operationsForGET() ){
for( Iterator it = directory.getFileServersIterator(op); it.hasNext();){
FileServer fs = (FileServer)it.next();
//assumption of same external mount point for each storage
//file server on output site
url = this.getURLOnStageoutSite( fs, lfn );
return url;
}
}//end of different get operations
return url;
}
/**
* This generates a error message for pool not found in the pool
* config file.
*
* @param poolName the name of pool that is not found.
* @param universe the condor universe
*
* @return the message.
*/
private String poolNotFoundMsg(String poolName, String universe) {
String st = "Error: No matching entry to pool = " + poolName +
" ,universe = " + universe +
"\n found in the pool configuration file ";
return st;
}
/**
* This gets the Vector of FileTransfer objects for all the files which have
* to be transferred to the destination pool in case of Interpool transfers.
* Each FileTransfer object has the source and the destination URLs. the
* source URI is determined from the pool on which the jobs are executed.
*
* @param job the job with reference to which interpool file transfers
* need to be determined.
* @param parents list <code>GraphNode</code> ojbects corresponding to the
* parent jobs of the job.
*
* @return array of Collection of <code>FileTransfer</code> objects
*/
private Collection<FileTransfer>[] getInterpoolFileTX(Job job, List<GraphNode>parents ) {
String destSiteHandle = job.getStagingSiteHandle();
//contains the remote_initialdir if specified for the job
String destRemoteDir = job.vdsNS.getStringValue(
Pegasus.REMOTE_INITIALDIR_KEY);
SiteCatalogEntry destSite = mSiteStore.lookup( destSiteHandle );
SiteCatalogEntry sourceSite;
Collection[] result = new Collection[2];
Collection<FileTransfer> localTransfers = new LinkedList();
Collection<FileTransfer> remoteTransfers = new LinkedList();
for ( GraphNode parent: parents ) {
//get the parent job
Job pJob = (Job)parent.getContent();
sourceSite = mSiteStore.lookup( pJob.getStagingSiteHandle() );
if( sourceSite.getSiteHandle().equalsIgnoreCase( destSiteHandle ) ){
//no need to add transfers, as the parent job and child
//job are run in the same directory on the pool
continue;
}
String sourceURI = null;
//PM-590 Stricter checks
/*
FileServer destSiteSharedScratchFS = destSite.selectHeadNodeScratchSharedFileServer( FileServer.OPERATION.put );
if( destSiteSharedScratchFS == null ){
this.complainForScratchFileServer( job, FileServer.OPERATION.put, destSiteHandle );
}
StringBuffer buffer = new StringBuffer();
buffer.append( destSiteSharedScratchFS.getURLPrefix() ).
append( mSiteStore.getExternalWorkDirectory(
destSiteSharedScratchFS,
destSiteHandle) );
String thirdPartyDestPutURI = buffer.toString();
*/
String thirdPartyDestPutURI = this.getURLOnSharedScratch( destSite, job, OPERATION.put, null );
//definite inconsitency as url prefix and mount point
//are not picked up from the same server
boolean localTransfer = runTransferOnLocalSite( destSiteHandle, thirdPartyDestPutURI, Job.INTER_POOL_JOB );
String destURI = localTransfer ?
//construct for third party transfer
thirdPartyDestPutURI :
//construct for normal transfer
"file://" + mSiteStore.getInternalWorkDirectory( destSiteHandle, destRemoteDir );
for (Iterator fileIt = pJob.getOutputFiles().iterator(); fileIt.hasNext(); ){
PegasusFile pf = (PegasusFile) fileIt.next();
String outFile = pf.getLFN();
if( job.getInputFiles().contains( pf ) ){
String sourceURL = null;
String destURL = destURI + File.separator + outFile;
String thirdPartyDestURL = thirdPartyDestPutURI + File.separator +
outFile;
FileTransfer ft = new FileTransfer(outFile,pJob.jobName);
ft.setSize( pf.getSize() );
ft.addDestination(destSiteHandle,destURL);
//for intersite transfers we need to track in transient rc
//for the cleanup algorithm
//only the destination is tracked as source will have been
//tracked for the parent jobs
trackInPlannerCache( outFile, thirdPartyDestURL, destSiteHandle );
//in the workflow cache we track the get URL for the outfile
String thirdPartyDestGetURL = this.getURLOnSharedScratch( destSite, job, OPERATION.get, outFile );
trackInWorkflowCache( outFile, thirdPartyDestGetURL, destSiteHandle );
//add all the possible source urls iterating through
//the list of grid ftp servers associated with the dest pool.
boolean first = true;
Directory parentScratchDir = mSiteStore.lookup( pJob.getStagingSiteHandle() ).getDirectory( Directory.TYPE.shared_scratch );
if( parentScratchDir == null ){
throw new RuntimeException( "Unable to determine the scratch dir for site " + pJob.getStagingSiteHandle() );
}
//retrive all the file servers matching the get operations
for( FileServer.OPERATION op : FileServer.OPERATION.operationsForGET() ){
for( Iterator it1 = parentScratchDir.getFileServersIterator(op); it1.hasNext(); ){
FileServer server = ( FileServer)it1.next();
//definite inconsitency as url prefix and mount point
//are not picked up from the same server
sourceURI = server.getURLPrefix();
//sourceURI += server.getMountPoint();
sourceURI += mSiteStore.getExternalWorkDirectory(server, pJob.getSiteHandle());
sourceURL = sourceURI + File.separator + outFile;
if(!(sourceURL.equalsIgnoreCase(thirdPartyDestURL))){
//add the source url only if it does not match to
//the third party destination url
ft.addSource(pJob.getStagingSiteHandle(), sourceURL);
}
first = false;
}
}
if( ft.isValid() ){
if( localTransfer ){
localTransfers.add(ft);
}
else{
remoteTransfers.add(ft);
}
}
}
}
}
result[0] = localTransfers;
result[1] = remoteTransfers;
return result;
}
/**
* Special Handling for a DAGJob for retrieving files from the Replica Catalog.
*
* @param job the DAGJob
* @param searchFiles file that need to be looked in the Replica Catalog.
*/
private void getFilesFromRC( DAGJob job, Collection searchFiles ){
//dax appears in adag element
String dag = null;
//go through all the job input files
//and set transfer flag to false
for (Iterator<PegasusFile> it = job.getInputFiles().iterator(); it.hasNext();) {
PegasusFile pf = it.next();
//at the moment dax files are not staged in.
//remove from input set of files
//part of the reason is about how to handle where
//to run the DAGJob. We dont have much control over it.
it.remove();
}
String lfn = job.getDAGLFN();
ReplicaLocation rl = mRCBridge.getFileLocs( lfn );
if (rl == null) { //flag an error
throw new RuntimeException(
"TransferEngine.java: Can't determine a location to " +
"transfer input file for DAG lfn " + lfn + " for job " +
job.getName());
}
ReplicaCatalogEntry selLoc = mReplicaSelector.selectReplica( rl,
job.getSiteHandle(),
true );
String pfn = selLoc.getPFN();
//some extra checks to ensure paths
if( pfn.startsWith( File.separator ) ){
dag = pfn;
}
else if( pfn.startsWith( PegasusURL.FILE_URL_SCHEME ) ){
// dag = Utility.getAbsolutePath( pfn );
dag = new PegasusURL( pfn ).getPath();
}
else{
throw new RuntimeException( "Invalid URL Specified for DAG Job " + job.getName() + " -> " + pfn );
}
job.setDAGFile(dag);
//set the directory if specified
job.setDirectory((String) job.dagmanVariables.removeKey(Dagman.DIRECTORY_EXTERNAL_KEY));
}
/**
* Special Handling for a DAXJob for retrieving files from the Replica Catalog.
*
* @param job the DAXJob
* @param searchFiles file that need to be looked in the Replica Catalog.
*/
private void getFilesFromRC( DAXJob job, Collection searchFiles ){
//dax appears in adag element
String dax = null;
//go through all the job input files
//and set transfer flag to false
for (Iterator<PegasusFile> it = job.getInputFiles().iterator(); it.hasNext();) {
PegasusFile pf = it.next();
//at the moment dax files are not staged in.
//remove from input set of files
//part of the reason is about how to handle where
//to run the DAGJob. We dont have much control over it.
it.remove();
}
String lfn = job.getDAXLFN();
ReplicaLocation rl = mRCBridge.getFileLocs( lfn );
if (rl == null) { //flag an error
throw new RuntimeException(
"TransferEngine.java: Can't determine a location to " +
"transfer input file for DAX lfn " + lfn + " for job " +
job.getName());
}
ReplicaCatalogEntry selLoc = mReplicaSelector.selectReplica( rl,
job.getSiteHandle(),
true );
String pfn = selLoc.getPFN();
//some extra checks to ensure paths
if( pfn.startsWith( File.separator ) ){
dax = pfn;
}
else if( pfn.startsWith( PegasusURL.FILE_URL_SCHEME ) ){
// dax = Utility.getAbsolutePath( pfn );
dax = new PegasusURL( pfn ).getPath();
}
else{
throw new RuntimeException( "Invalid URL Specified for DAX Job " + job.getName() + " -> " + pfn );
}
//add the dax to the argument
StringBuffer arguments = new StringBuffer();
arguments.append(job.getArguments()).
append(" --dax ").append(dax);
job.setArguments(arguments.toString());
}
/**
* It looks up the RCEngine Hashtable to lookup the locations for the
* files and add nodes to transfer them. If a file is not found to be in
* the Replica Catalog the Transfer Engine flags an error and exits
*
* @param job the <code>Job</code>object for whose ipfile have
* to search the Replica Mechanism for.
* @param searchFiles Vector containing the PegasusFile objects corresponding
* to the files that need to have their mapping looked
* up from the Replica Mechanism.
*/
private void getFilesFromRC( Job job, Collection searchFiles ) {
//Vector vFileTX = new Vector();
//Collection<FileTransfer> symLinkFileTransfers = new LinkedList();
Collection<FileTransfer> localFileTransfers = new LinkedList();
Collection<FileTransfer> remoteFileTransfers = new LinkedList();
String jobName = job.logicalName;
String stagingSiteHandle = job.getStagingSiteHandle();
//contains the remote_initialdir if specified for the job
String eRemoteDir = job.vdsNS.getStringValue(
Pegasus.REMOTE_INITIALDIR_KEY);
SiteCatalogEntry stagingSite = mSiteStore.lookup( stagingSiteHandle );
//we are using the pull mode for data transfer
String scheme = "file";
//sAbsPath would be just the source directory absolute path
//dAbsPath would be just the destination directory absolute path
/*
//PM-590 Stricter checks
FileServer stagingSiteSharedScratchFS = stagingSite.selectHeadNodeScratchSharedFileServer( FileServer.OPERATION.put );
if( stagingSiteSharedScratchFS == null ){
this.complainForScratchFileServer( job, FileServer.OPERATION.put, stagingSiteHandle);
}
String dAbsPath = mSiteStore.getExternalWorkDirectory( stagingSiteSharedScratchFS,
stagingSiteHandle);
String sAbsPath = null;
//sDirURL would be the url to the source directory.
//dDirPutURL would be the url to the destination directoy
//and is always a networked url.
String dDirPutURL = stagingSiteSharedScratchFS.getURLPrefix() + dAbsPath;
*/
//sDirURL would be the url to the source directory.
//dDirPutURL would be the url to the destination directoy
//and is always a networked url.
String dDirPutURL = this.getURLOnSharedScratch( stagingSite, job, OPERATION.put, null );
String dDirGetURL = this.getURLOnSharedScratch( stagingSite, job, OPERATION.get, null );
String sDirURL = null;
String sAbsPath = null;
String dAbsPath = mSiteStore.getInternalWorkDirectory( stagingSiteHandle, eRemoteDir );
//file dest dir is destination dir accessed as a file URL
String fileDestDir = scheme + "://" + dAbsPath;
//check if the execution pool is third party or not
boolean runTransferOnLocalSite = runTransferOnLocalSite( stagingSiteHandle, dDirPutURL, Job.STAGE_IN_JOB);
String destDir = ( runTransferOnLocalSite ) ?
//use the full networked url to the directory
dDirPutURL
:
//use the default pull mode
fileDestDir;
for( Iterator it = searchFiles.iterator(); it.hasNext(); ){
String sourceURL = null,destPutURL = null, destGetURL =null;
PegasusFile pf = (PegasusFile) it.next();
List pfns = null;
ReplicaLocation rl = null;
String lfn = pf.getLFN();
NameValue nv = null;
//see if the pf is infact an instance of FileTransfer
if( pf instanceof FileTransfer ){
//that means we should be having the source url already.
//nv contains both the source pool and the url.
//This happens in case of AI Planner or transfer of executables
nv = ((FileTransfer)pf).getSourceURL();
NameValue destNV = ((FileTransfer)pf).removeDestURL();
if( destNV == null ){
//the source URL was specified in the DAX
//no transfer of executables case
throw new RuntimeException( "Unreachable code . Signifies error in internal logic " );
}
else{
//staging of executables case
destPutURL = destNV.getValue();
destPutURL = (runTransferOnLocalSite( stagingSiteHandle, destPutURL, Job.STAGE_IN_JOB))?
//the destination URL is already third party
//enabled. use as it is
destPutURL:
//explicitly convert to file URL scheme
scheme + "://" + new PegasusURL( destPutURL ).getPath();
//for time being for this case the get url is same as put url
destGetURL = destPutURL;
}
}
else{
//query the replica services and get hold of pfn
rl = mRCBridge.getFileLocs( lfn );
pfns = (rl == null) ? null: rl.getPFNList();
}
if ( pfns == null && nv == null ) {
//check to see if the input file is optional
if(pf.fileOptional()){
//no need to add a transfer node for it if no location found
//remove the PegasusFile object from the list of
//input files for the job
boolean removed = job.getInputFiles().remove( pf );
//System.out.println( "Removed " + pf.getLFN() + " " + removed );
continue;
}
//flag an error
throw new RuntimeException(
"TransferEngine.java: Can't determine a location to " +
"transfer input file for lfn " + lfn + " for job " +
job.getName());
}
ReplicaCatalogEntry selLoc = (nv == null)?
//select from the various replicas
mReplicaSelector.selectReplica( rl,
job.getSiteHandle(),
runTransferOnLocalSite ):
//we have the replica already selected
new ReplicaCatalogEntry( nv.getValue(), nv.getKey() );
//check if we need to replace url prefix for
//symbolic linking
boolean symLinkSelectedLocation;
if ( symLinkSelectedLocation =
(mUseSymLinks && selLoc.getResourceHandle().equals( job.getStagingSiteHandle() )) ) {
//resolve any srm url's that are specified
selLoc = replaceSourceProtocolFromURL( selLoc );
}
//get the file to the job's execution pool
//this is assuming that there are no directory paths
//in the pfn!!!
sDirURL = selLoc.getPFN().substring( 0, selLoc.getPFN().lastIndexOf(File.separator) );
//try to get the directory absolute path
//yes i know that we sending the url to directory
//not the file.
sAbsPath = new PegasusURL( sDirURL ).getPath();
//the final source and destination url's to the file
sourceURL = selLoc.getPFN();
if( destPutURL == null ){
//no staging of executables case.
//we construct destination URL to file.
StringBuffer destPFN = new StringBuffer();
if( symLinkSelectedLocation ){
//we use the file URL location to dest dir
//in case we are symlinking
//destPFN.append( fileDestDir );
destPFN.append( this.replaceProtocolFromURL( destDir ) );
}
else{
//we use whatever destDir was set to earlier
destPFN.append( destDir );
}
destPFN.append( File.separator).append( lfn );
destPutURL = destPFN.toString();
destGetURL = dDirGetURL + File.separator + lfn;
}
//we have all the chopped up combos of the urls.
//do some funky matching on the basis of the fact
//that each pool has one shared filesystem
//match the source and dest 3rd party urls or
//match the directory url knowing that lfn and
//(source and dest pool) are same
try{
if(sourceURL.equalsIgnoreCase(dDirPutURL + File.separator + lfn)||
( selLoc.getResourceHandle().equalsIgnoreCase( stagingSiteHandle ) &&
lfn.equals( sourceURL.substring(sourceURL.lastIndexOf(File.separator) + 1)) &&
//sAbsPath.equals( dAbsPath )
new File( sAbsPath ).getCanonicalPath().equals( new File( dAbsPath).getCanonicalPath())
)
){
//do not need to add any transfer node
StringBuffer message = new StringBuffer( );
message.append( sAbsPath ).append( " same as " ).append( dAbsPath );
mLogger.log( message.toString() , LogManager.DEBUG_MESSAGE_LEVEL );
message = new StringBuffer();
message.append( " Not transferring ip file as ").append( lfn ).
append( " for job " ).append( job.jobName ).append( " to site " ).append( stagingSiteHandle );
mLogger.log( message.toString() , LogManager.DEBUG_MESSAGE_LEVEL );
continue;
}
}catch( IOException ioe ){
/*ignore */
}
//add locations of input data on the remote site to the transient RC
boolean bypassFirstLevelStaging = this.bypassStagingForInputFile( selLoc , pf , job.getSiteHandle() );
if( bypassFirstLevelStaging ){
//only the files for which we bypass first level staging , we
//store them in the planner cache as a GET URL and associate with the compute site
//PM-698
trackInPlannerCache( lfn, sourceURL, selLoc.getResourceHandle(), OPERATION.get );
trackInWorkflowCache( lfn, sourceURL, selLoc.getResourceHandle() );
//ensure the input file does not get cleaned up by the
//InPlace cleanup algorithm
pf.setForCleanup( false );
continue;
}
else{
//track the location where the data is staged as
//part of the first level staging
//we always store the thirdparty url
//trackInCaches( lfn, destPutURL, job.getSiteHandle() );
trackInPlannerCache( lfn,
destPutURL,
job.getStagingSiteHandle());
trackInWorkflowCache( lfn,
destGetURL,
job.getStagingSiteHandle());
}
//construct the file transfer object
FileTransfer ft = (pf instanceof FileTransfer) ?
(FileTransfer)pf:
new FileTransfer( lfn, jobName, pf.getFlags() );
//make sure the type information is set in file transfer
ft.setType( pf.getType() );
ft.setSize( pf.getSize() );
//the transfer mode for the file needs to be
//propogated for optional transfers.
ft.setTransferFlag(pf.getTransferFlag());
//to prevent duplicate source urls
if(ft.getSourceURL() == null){
ft.addSource( selLoc.getResourceHandle(), sourceURL);
}
//to prevent duplicate destination urls
if(ft.getDestURL() == null)
ft.addDestination(stagingSiteHandle,destPutURL);
if( symLinkSelectedLocation || !runTransferOnLocalSite ){
//all symlink transfers and user specified remote transfers
remoteFileTransfers.add(ft);
}
else{
localFileTransfers.add(ft);
}
//we need to set destPutURL to null
destPutURL = null;
}
//call addTransferNode
if (!localFileTransfers.isEmpty() || !remoteFileTransfers.isEmpty()) {
mTXRefiner.addStageInXFERNodes(job, localFileTransfers, remoteFileTransfers );
}
}
/**
* Replaces the SRM URL scheme from the url, and replaces it with the
* file url scheme and returns in a new object if replacement happens.
* The original object passed as a parameter still remains the same.
*
* @param rce the <code>ReplicaCatalogEntry</code> object whose url need to be
* replaced.
*
* @return the object with the url replaced.
*/
protected ReplicaCatalogEntry replaceSourceProtocolFromURL( ReplicaCatalogEntry rce ) {
String pfn = rce.getPFN();
//if the pfn starts with a file url we
//dont need to replace . a sanity check
if( pfn.startsWith( PegasusURL.FILE_URL_SCHEME ) ){
return rce;
}
/* special handling for SRM urls */
StringBuffer newPFN = new StringBuffer();
if( mSRMServiceURLToMountPointMap.containsKey( rce.getResourceHandle() ) ){
//try to do replacement of URL with internal mount point
NameValue nv = mSRMServiceURLToMountPointMap.get( rce.getResourceHandle() );
String urlPrefix = nv.getKey();
if( pfn.startsWith( urlPrefix ) ){
//replace the starting with the mount point
newPFN.append( PegasusURL.FILE_URL_SCHEME ).append( "//" );
newPFN.append( nv.getValue() );
newPFN.append( pfn.substring( urlPrefix.length(), pfn.length() ));
mLogger.log( "Replaced pfn " + pfn + " with " + newPFN.toString() ,
LogManager.TRACE_MESSAGE_LEVEL );
}
}
if( newPFN.length() == 0 ){
//there is no SRM Replacement to do
//Still do the FILE replacement
//return the original object
//we have to the manual replacement
/*
String hostName = Utility.getHostName( pfn );
newPFN.append( FILE_URL_SCHEME ).append( "//" );
//we want to skip out the hostname
newPFN.append( pfn.substring( pfn.indexOf( hostName ) + hostName.length() ) );
*/
newPFN.append( PegasusURL.FILE_URL_SCHEME ).append( "//" );
newPFN.append( new PegasusURL( pfn ).getPath() );
}
//we do not need a full clone, just the PFN
ReplicaCatalogEntry result = new ReplicaCatalogEntry( newPFN.toString(),
rce.getResourceHandle() );
for( Iterator it = rce.getAttributeIterator(); it.hasNext();){
String key = (String)it.next();
result.addAttribute( key, rce.getAttribute( key ) );
}
return result;
}
/**
* Replaces the gsiftp URL scheme from the url, and replaces it with the
* symlink url scheme and returns in a new object. The original object
* passed as a parameter still remains the same.
*
* @param pfn the pfn that needs to be replaced
*
* @return the replaced PFN
*/
protected String replaceProtocolFromURL( String pfn ) {
/* special handling for SRM urls */
StringBuffer newPFN = new StringBuffer();
if( pfn.startsWith(PegasusURL.FILE_URL_SCHEME) ){
//special handling for FILE URL's as
//utility hostname functions dont hold up
newPFN.append( PegasusURL.SYMLINK_URL_SCHEME ).
append( pfn.substring( PegasusURL.FILE_URL_SCHEME.length() ) );
//System.out.println( "Original PFN " + pfn + " \nReplaced PFN " + newPFN.toString() );
return newPFN.toString();
}
newPFN.append( PegasusURL.SYMLINK_URL_SCHEME ).append( "//" );
//we want to skip out the hostname
newPFN.append( new PegasusURL( pfn ).getPath() );
return newPFN.toString();
}
/**
* Constructs a Properties objects by parsing the relevant SRM
* pegasus properties.
*
* For example, if users have the following specified in properties file
* <pre>
* pegasus.transfer.srm.ligo-cit.service.url srm://osg-se.ligo.caltech.edu:10443/srm/v2/server?SFN=/mnt/hadoop
* pegasus.transfer.srm.ligo-cit.service.mountpoint /mnt/hadoop
* </pre>
*
* then, a Map is create the associates ligo-cit with NameValue object
* containing the service url and mount point ( ).
*
* @param props the <code>PegasusProperties</code> object
*
* @return Map that maps a site name to a NameValue object that has the
* URL prefix and the mount point
*/
private Map<String, NameValue> constructSiteToSRMServerMap( PegasusProperties props ) {
Map<String, NameValue> m = new HashMap();
//first strip of prefix from properties and get matching subset
Properties siteProps = props.matchingSubset( TransferEngine.SRM_PROPERTIES_PREFIX, false );
//retrieve all the sites for which SRM servers are specified
Map<String, String> m1 = new HashMap(); //associates site name to url prefix
Map<String, String> m2 = new HashMap(); //associates site name to mount point
for( Iterator it = siteProps.keySet().iterator(); it.hasNext(); ){
String key = (String) it.next();
//determine the site name
String site = key.substring( 0, key.indexOf( "." ) );
if( key.endsWith( TransferEngine.SRM_SERVICE_URL_PROPERTIES_SUFFIX ) ){
m1.put( site, siteProps.getProperty( key ) );
}
else if( key.endsWith( TransferEngine.SRM_MOUNT_POINT_PROPERTIES_SUFFIX ) ){
m2.put( site, siteProps.getProperty( key ) );
}
}
//now merge the information into m and return
for( Iterator <Map.Entry<String, String>>it = m1.entrySet().iterator(); it.hasNext(); ){
Map.Entry<String, String> entry = it.next();
String site = entry.getKey();
String url = entry.getValue();
String mountPoint = m2.get( site );
if( mountPoint == null ){
mLogger.log( "Mount Point for SRM server not specified in properties for site " + site,
LogManager.WARNING_MESSAGE_LEVEL );
continue;
}
m.put( site, new NameValue( url, mountPoint ) );
}
mLogger.log( "SRM Server map is " + m,
LogManager.DEBUG_MESSAGE_LEVEL );
return m;
}
/**
* It gets the output files for all the nodes which are specified in
* the nodes passed.
*
* @param nodes List<GraphNode> containing the jobs
*
*
* @return Set of PegasusFile objects
*/
private Set<PegasusFile> getOutputFiles( List<GraphNode> nodes ) {
Set<PegasusFile> files = new HashSet();
for( GraphNode n : nodes ){
Job job = (Job)n.getContent();
files.addAll( job.getOutputFiles() );
}
return files;
}
/**
* Initialize the Stageout Site Directory factory.
* The factory is used to returns the relative directory that a particular
* file needs to be staged to on the output site.
*
* @param workflow the workflow to which the transfer nodes need to be
* added.
*
*/
protected void initializeStageOutSiteDirectoryFactory( ADag workflow ){
String outputSite = mPOptions.getOutputSite();
boolean stageOut = (( outputSite != null ) && ( outputSite.trim().length() > 0 ));
if (!stageOut ){
//no initialization and return
mLogger.log( "No initialization of StageOut Site Directory Factory",
LogManager.DEBUG_MESSAGE_LEVEL );
return;
}
// create files in the directory, unless anything else is known.
SiteCatalogEntry entry = mSiteStore.lookup( outputSite );
if( entry == null ){
throw new RuntimeException( "Unable to lookup site catalog for site " + outputSite );
}
mStageoutDirectory = entry.getHeadNodeStorageDirectory();
if( mStageoutDirectory == null ){
throw new RuntimeException( "No Storage directory specified for site " + outputSite );
}
// mStageOutBaseDirectory = mSiteStore.getExternalStorageDirectory( outputSite );
String addOn = mSiteStore.getRelativeStorageDirectoryAddon( );
//all file factories intialized with the addon component only
if( this.mDeepStorageStructure ){
// create hashed, and levelled directories
try {
VirtualDecimalHashedFileFactory temp = null;
//get the total number of files that need to be stageout
int totalFiles = 0;
for ( Iterator it = workflow.jobIterator(); it.hasNext(); ){
Job job = ( Job )it.next();
//traverse through all the job output files
for( Iterator opIt = job.getOutputFiles().iterator(); opIt.hasNext(); ){
if( !((PegasusFile)opIt.next()).getTransientTransferFlag() ){
//means we have to stage to output site
totalFiles++;
}
}
}
// temp = new VirtualDecimalHashedFileFactory( mStageOutBaseDirectory, totalFiles );
temp = new VirtualDecimalHashedFileFactory( addOn, totalFiles );
//each stageout file has only 1 file associated with it
temp.setMultiplicator( 1 );
mFactory = temp;
}
catch (IOException e) {
//wrap into runtime and throw
throw new RuntimeException( "While initializing HashedFileFactory", e );
}
}
else{
try {
//Create a flat file factory
// mFactory = new VirtualFlatFileFactory( mStageOutBaseDirectory ); // minimum default
mFactory = new VirtualFlatFileFactory( addOn ); // minimum default
} catch ( IOException ioe ) {
throw new RuntimeException( "Unable to generate files in the submit directory " ,
ioe );
}
}
}
/**
* Tracks the files created by a job in the both the planner and workflow cache
* The planner cache stores the put URL's and the GET URL is stored in the
* workflow cache.
*
* @param job the job whose input files need to be tracked.
*/
private void trackInCaches( Job job ){
//check if there is a remote initialdir set
String path = job.vdsNS.getStringValue(
Pegasus.REMOTE_INITIALDIR_KEY );
SiteCatalogEntry stagingSiteEntry = mSiteStore.lookup( job.getStagingSiteHandle() );
if ( stagingSiteEntry == null ) {
this.poolNotFoundMsg( job.getStagingSiteHandle(), "vanilla" ) ;
mLogger.log( mLogMsg, LogManager.ERROR_MESSAGE_LEVEL );
throw new RuntimeException( mLogMsg );
}
for( Iterator it = job.getOutputFiles().iterator(); it.hasNext(); ){
PegasusFile pf = (PegasusFile) it.next();
String lfn = pf.getLFN();
//construct the URL to track in planner cache
String stagingSitePutURL = this.getURLOnSharedScratch( stagingSiteEntry, job, OPERATION.put, lfn);
trackInPlannerCache( lfn, stagingSitePutURL, stagingSiteEntry.getSiteHandle() );
String stagingSiteGetURL = this.getURLOnSharedScratch( stagingSiteEntry, job, OPERATION.get, lfn);
trackInWorkflowCache( lfn, stagingSiteGetURL, stagingSiteEntry.getSiteHandle() );
}
}
/**
* Inserts an entry into the planner cache as a put URL.
*
*
* @param lfn the logical name of the file.
* @param pfn the pfn
* @param site the site handle
*/
private void trackInPlannerCache( String lfn,
String pfn,
String site ){
trackInPlannerCache( lfn, pfn, site, OPERATION.put );
}
/**
* Inserts an entry into the planner cache as a put URL.
*
*
* @param lfn the logical name of the file.
* @param pfn the pfn
* @param site the site handle
* @param type the type of url
*/
private void trackInPlannerCache( String lfn,
String pfn,
String site,
OPERATION type ){
mPlannerCache.insert( lfn, pfn, site, type );
}
/**
* Inserts an entry into the workflow cache that is to be written out to the
* submit directory.
*
* @param lfn the logical name of the file.
* @param pfn the pfn
* @param site the site handle
*/
private void trackInWorkflowCache( String lfn,
String pfn,
String site ){
mWorkflowCache.insert( lfn, pfn, site );
}
/**
* Returns a URL on the shared scratch of the staging site
*
* @param entry the SiteCatalogEntry for the associated stagingsite
* @param job the job
* @param operation the FileServer operation for which we need the URL
* @param lfn the LFN can be null to get the path to the directory
*
* @return the URL
*/
private String getURLOnSharedScratch( SiteCatalogEntry entry ,
Job job,
FileServer.OPERATION operation ,
String lfn ){
StringBuffer url = new StringBuffer();
FileServer getServer = entry.selectHeadNodeScratchSharedFileServer( operation );
if( getServer == null ){
this.complainForScratchFileServer(job, operation, entry.getSiteHandle());
}
url.append( getServer.getURLPrefix() ).
append( mSiteStore.getExternalWorkDirectory(getServer, entry.getSiteHandle() ));
if( lfn != null ){
url.append( File.separatorChar ).append( lfn );
}
return url.toString();
}
/**
* Returns the full path on remote output site, where the lfn will reside.
* Each call to this function could trigger a change in the directory
* returned depending upon the file factory being used.
*
* @param directory the directory on the output site
* @param operation the get or put operation
* @param lfn the lfn
*
* @return the URL as a String
*/
private String getURLOnStageoutSite(Directory directory, OPERATION operation, String lfn) {
//PM-590 stricter checks
FileServer server = directory.selectFileServer( operation );
// String urlPrefix = p.selectHeadNodeScratchSharedFileServerURLPrefix( FileServer.OPERATION.put );
if( server == null ){
this.complainForStorageFileServer( "", operation, this.mPlannerOptions.getOutputSite() );
}
return this.getURLOnStageoutSite( server, lfn );
}
/**
* Returns the full path on remote output site, where the lfn will reside.
* Each call to this function could trigger a change in the directory
* returned depending upon the file factory being used.
*
* @param server the file server to use
* @param lfn the logical filename of the file.
*
* @return the storage mount point.
*/
private String getURLOnStageoutSite( FileServer server, String lfn ){
StringBuffer url = new StringBuffer( server.getURL() );
try{
//the factory will give us the relative
//add on part
String addOn = mFactory.createFile( lfn ).toString();
//check if we need to add file separator
//do we really need it?
if( addOn.indexOf( File.separator ) != 0 ){
url.append( File.separator );
}
url.append( addOn );
}
catch( IOException e ){
throw new RuntimeException( "IOException " , e );
}
return url.toString();
}
/**
* Complains for a missing head node storage file server on a site for a job
*
* @param job the job
* @param operation the operation
* @param site the site
*/
private void complainForStorageFileServer( Job job,
FileServer.OPERATION operation,
String site) {
this.complainForScratchFileServer( job.getID(), operation, site);
}
/**
* Complains for a missing head node storage file server on a site for a job
*
* @param jobname the name of the job
* @param operation the file server operation
* @param site the site
*/
private void complainForStorageFileServer( String jobname,
FileServer.OPERATION operation,
String site) {
StringBuffer error = new StringBuffer();
error.append( "[" ).append( REFINER_NAME ).append( "] ");
if( jobname != null ){
error.append( "For job (" ).append( jobname).append( ")." );
}
error.append( " File Server not specified for shared-scratch filesystem for site: ").
append( site );
throw new RuntimeException( error.toString() );
}
/**
* Complains for a missing head node file server on a site for a job
*
* @param job the job
* @param operation the operation
* @param site the site
*/
private void complainForScratchFileServer( Job job,
FileServer.OPERATION operation,
String site) {
this.complainForScratchFileServer( job.getID(), operation, site);
}
/**
* Complains for a missing head node file server on a site for a job
*
* @param jobname the name of the job
* @param operation the file server operation
* @param site the site
*/
private void complainForScratchFileServer( String jobname,
FileServer.OPERATION operation,
String site) {
StringBuffer error = new StringBuffer();
error.append( "[" ).append( REFINER_NAME ).append( "] ");
if( jobname != null ){
error.append( "For job (" ).append( jobname).append( ")." );
}
error.append( " File Server not specified for shared-scratch filesystem for site: ").
append( site );
throw new RuntimeException( error.toString() );
}
/**
* Initializes a Replica Catalog Instance that is used to store
* the GET URL's for all files on the staging site ( inputs staged and outputs
* created ).
*
* @param dag the workflow being planned
*
* @return handle to transient catalog
*/
private ReplicaCatalog initializeWorkflowCacheFile( ADag dag ){
ReplicaCatalog rc = null;
mLogger.log("Initialising Workflow Cache File in the Submit Directory",
LogManager.DEBUG_MESSAGE_LEVEL );
Properties cacheProps = mProps.getVDSProperties().matchingSubset(
ReplicaCatalog.c_prefix,
false );
String file = mPOptions.getSubmitDirectory() + File.separatorChar +
getCacheFileName( dag );
//set the appropriate property to designate path to file
cacheProps.setProperty( WORKFLOW_CACHE_REPLICA_CATALOG_KEY, file );
try{
rc = ReplicaFactory.loadInstance(
WORKFLOW_CACHE_FILE_IMPLEMENTOR,
cacheProps);
}
catch( Exception e ){
throw new RuntimeException( "Unable to initialize Workflow Cache File in the Submit Directory " + file,
e );
}
return rc;
}
/**
* Constructs the basename to the cache file that is to be used
* to log the transient files. The basename is dependant on whether the
* basename prefix has been specified at runtime or not.
*
* @param adag the ADag object containing the workflow that is being
* concretized.
*
* @return the name of the cache file
*/
private String getCacheFileName(ADag adag){
StringBuffer sb = new StringBuffer();
String bprefix = mPOptions.getBasenamePrefix();
if(bprefix != null){
//the prefix is not null using it
sb.append(bprefix);
}
else{
//generate the prefix from the name of the dag
sb.append(adag.dagInfo.nameOfADag).append("-").
append(adag.dagInfo.index);
}
//append the suffix
sb.append(".cache");
return sb.toString();
}
/**
* Returns a boolean indicating whether to bypass first level staging for a
* file or not
*
* @param entry a ReplicaCatalogEntry matching the selected replica location.
* @param file the corresponding Pegasus File object
* @param computeSite the compute site where the associated job will run.
* @param isExecutable whether the file transferred is an executable file or not
*
* @return boolean indicating whether we need to enable bypass or not
*/
private boolean bypassStagingForInputFile( ReplicaCatalogEntry entry , PegasusFile file, String computeSite ) {
boolean bypass = false;
//check if user has it configured for bypassing the staging and
//we are in pegasus lite mode
if( this.mBypassStagingForInputs && mWorkerNodeExecution ){
boolean isFileURL = entry.getPFN().startsWith( PegasusURL.FILE_URL_SCHEME);
String fileSite = entry.getResourceHandle();
if( this.mSetupForCondorIO ){
//additional check for condor io
//we need to inspect the URL and it's location
if( isFileURL &&
fileSite.equals( "local" ) ){
//for condorio only file urls for input files are
//eligible for bypass
bypass = ( file.isExecutable() )?
//for condor io, we cannot remap the destination URL
//we need to make sure the PFN ends with lfn to enable bypass
entry.getPFN().endsWith( file.getLFN() ):
true;
}
}
else{
//for non shared fs case we can bypass all url's safely
//other than file urls
bypass = isFileURL ?
fileSite.equalsIgnoreCase( computeSite )://file site is same as the compute site
true;
}
}
return bypass;
}
}
| PM-698 In CondorIO mode for bypassing staging of files, we need to
check if the source URL ends with the LFN, as we cannot rename
destinations in CondorIO.
| src/edu/isi/pegasus/planner/refiner/TransferEngine.java | PM-698 In CondorIO mode for bypassing staging of files, we need to check if the source URL ends with the LFN, as we cannot rename destinations in CondorIO. | <ide><path>rc/edu/isi/pegasus/planner/refiner/TransferEngine.java
<ide> if( this.mSetupForCondorIO ){
<ide> //additional check for condor io
<ide> //we need to inspect the URL and it's location
<add> //only file urls for input files are eligible for bypass
<ide> if( isFileURL &&
<ide> fileSite.equals( "local" ) ){
<del> //for condorio only file urls for input files are
<del> //eligible for bypass
<del> bypass = ( file.isExecutable() )?
<del> //for condor io, we cannot remap the destination URL
<del> //we need to make sure the PFN ends with lfn to enable bypass
<del> entry.getPFN().endsWith( file.getLFN() ):
<del> true;
<add> //in condor io we cannot remap the destination URL
<add> //we need to make sure the PFN ends with lfn to enable bypass
<add> bypass = entry.getPFN().endsWith( file.getLFN() );
<ide> }
<ide> }
<ide> else{ |
|
Java | mit | ccc83f620ec1bab6f96f67b32fba9668a81f96de | 0 | anotheria/moskito,esmakula/moskito,esmakula/moskito,esmakula/moskito,anotheria/moskito,esmakula/moskito,anotheria/moskito,anotheria/moskito | package net.anotheria.moskito.webui.gauges.api;
import net.anotheria.moskito.core.decorators.value.StatValueAO;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
/**
* Represents a gauge with its values.
*
* @author lrosenberg
* @since 23.03.15 21:40
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
public class GaugeAO implements Serializable{
/**
* SerialVersionUID.
*/
private static final long serialVersionUID = 1554363798887359631L;
/**
* Name of the gauge.
*/
private String name;
/**
* Caption of the gauge box.
*/
private String caption;
/**
* Min value.
*/
private StatValueAO min;
/**
* Current value.
*/
private StatValueAO current;
/**
* Max value.
*/
private StatValueAO max;
/**
* Could all values be set?
*/
private boolean complete;
/**
* Zones associated with this gauge.
*/
private List<GaugeZoneAO> zones = new LinkedList<GaugeZoneAO>();
public StatValueAO getCurrent() {
return current;
}
public void setCurrent(StatValueAO current) {
this.current = current;
}
public StatValueAO getMax() {
return max;
}
public void setMax(StatValueAO max) {
this.max = max;
}
public StatValueAO getMin() {
return min;
}
public void setMin(StatValueAO min) {
this.min = min;
}
@XmlElement(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement(name="complete")
public boolean isComplete() {
return complete;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
@XmlElement(name="current")
public String getCurrentValue(){
return current.getRawValue();
}
@XmlElement(name="min")
public String getMinValue(){
return min.getRawValue();
}
@XmlElement(name="max")
public String getMaxValue(){
return max.getRawValue();
}
@Override
public String toString() {
return "GaugeAO{" +
"name="+name+
", current=" + current +
", min=" + min +
", max=" + max +
", zones= "+zones+
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GaugeAO gaugeAO = (GaugeAO) o;
return name.equals(gaugeAO.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public List<GaugeZoneAO> getZones() {
return zones;
}
public void setZones(List<GaugeZoneAO> zones) {
this.zones = zones;
}
public void addZone(GaugeZoneAO zone){
zones.add(zone);
}
public boolean getCustomZonesAvailable(){
return zones!=null && zones.size()>0;
}
}
| moskito-webui/src/main/java/net/anotheria/moskito/webui/gauges/api/GaugeAO.java | package net.anotheria.moskito.webui.gauges.api;
import net.anotheria.moskito.core.decorators.value.StatValueAO;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
/**
* Represents a gauge with its values.
*
* @author lrosenberg
* @since 23.03.15 21:40
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
public class GaugeAO implements Serializable{
/**
* SerialVersionUID.
*/
private static final long serialVersionUID = 1554363798887359631L;
/**
* Name of the gauge.
*/
private String name;
/**
* Caption of the gauge box.
*/
private String caption;
/**
* Min value.
*/
private StatValueAO min;
/**
* Current value.
*/
private StatValueAO current;
/**
* Max value.
*/
private StatValueAO max;
/**
* Could all values be set?
*/
private boolean complete;
/**
* Zones associated with this gauge.
*/
private List<GaugeZoneAO> zones = new LinkedList<GaugeZoneAO>();
public StatValueAO getCurrent() {
return current;
}
public void setCurrent(StatValueAO current) {
this.current = current;
}
public StatValueAO getMax() {
return max;
}
public void setMax(StatValueAO max) {
this.max = max;
}
public StatValueAO getMin() {
return min;
}
public void setMin(StatValueAO min) {
this.min = min;
}
@XmlElement(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement(name="complete")
public boolean isComplete() {
return complete;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
@XmlElement(name="current")
public String getCurrentValue(){
return current.getRawValue();
}
@XmlElement(name="min")
public String getMinValue(){
return min.getRawValue();
}
@XmlElement(name="max")
public String getMaxValue(){
return max.getRawValue();
}
@Override
public String toString() {
return "GaugeAO{" +
"name="+name+
", current=" + current +
", min=" + min +
", max=" + max +
", zones= "+zones+
'}';
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public List<GaugeZoneAO> getZones() {
return zones;
}
public void setZones(List<GaugeZoneAO> zones) {
this.zones = zones;
}
public void addZone(GaugeZoneAO zone){
zones.add(zone);
}
public boolean getCustomZonesAvailable(){
return zones!=null && zones.size()>0;
}
}
| MSK-383 Gauge control
| moskito-webui/src/main/java/net/anotheria/moskito/webui/gauges/api/GaugeAO.java | MSK-383 Gauge control | <ide><path>oskito-webui/src/main/java/net/anotheria/moskito/webui/gauges/api/GaugeAO.java
<ide> '}';
<ide> }
<ide>
<add> @Override
<add> public boolean equals(Object o) {
<add> if (this == o) return true;
<add> if (o == null || getClass() != o.getClass()) return false;
<add>
<add> GaugeAO gaugeAO = (GaugeAO) o;
<add>
<add> return name.equals(gaugeAO.name);
<add>
<add> }
<add>
<add> @Override
<add> public int hashCode() {
<add> return name.hashCode();
<add> }
<add>
<ide> public String getCaption() {
<ide> return caption;
<ide> } |
|
Java | apache-2.0 | 8da7fc7d2f04982c44075be4f6a8e62459459594 | 0 | androidx/media,ened/ExoPlayer,google/ExoPlayer,google/ExoPlayer,androidx/media,amzn/exoplayer-amazon-port,amzn/exoplayer-amazon-port,amzn/exoplayer-amazon-port,androidx/media,ened/ExoPlayer,ened/ExoPlayer,google/ExoPlayer | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.source.hls.playlist;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.drm.DrmInitData.SchemeData;
import com.google.android.exoplayer2.extractor.mp4.PsshAtomUtil;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.source.UnrecognizedInputFormatException;
import com.google.android.exoplayer2.source.hls.HlsTrackMetadataEntry;
import com.google.android.exoplayer2.source.hls.HlsTrackMetadataEntry.VariantInfo;
import com.google.android.exoplayer2.source.hls.playlist.HlsMasterPlaylist.Rendition;
import com.google.android.exoplayer2.source.hls.playlist.HlsMasterPlaylist.Variant;
import com.google.android.exoplayer2.source.hls.playlist.HlsMediaPlaylist.Segment;
import com.google.android.exoplayer2.upstream.ParsingLoadable;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.UriUtil;
import com.google.android.exoplayer2.util.Util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
import org.checkerframework.checker.nullness.qual.PolyNull;
/**
* HLS playlists parsing logic.
*/
public final class HlsPlaylistParser implements ParsingLoadable.Parser<HlsPlaylist> {
private static final String PLAYLIST_HEADER = "#EXTM3U";
private static final String TAG_PREFIX = "#EXT";
private static final String TAG_VERSION = "#EXT-X-VERSION";
private static final String TAG_PLAYLIST_TYPE = "#EXT-X-PLAYLIST-TYPE";
private static final String TAG_DEFINE = "#EXT-X-DEFINE";
private static final String TAG_STREAM_INF = "#EXT-X-STREAM-INF";
private static final String TAG_I_FRAME_STREAM_INF = "#EXT-X-I-FRAME-STREAM-INF";
private static final String TAG_IFRAME = "#EXT-X-I-FRAMES-ONLY";
private static final String TAG_MEDIA = "#EXT-X-MEDIA";
private static final String TAG_TARGET_DURATION = "#EXT-X-TARGETDURATION";
private static final String TAG_DISCONTINUITY = "#EXT-X-DISCONTINUITY";
private static final String TAG_DISCONTINUITY_SEQUENCE = "#EXT-X-DISCONTINUITY-SEQUENCE";
private static final String TAG_PROGRAM_DATE_TIME = "#EXT-X-PROGRAM-DATE-TIME";
private static final String TAG_INIT_SEGMENT = "#EXT-X-MAP";
private static final String TAG_INDEPENDENT_SEGMENTS = "#EXT-X-INDEPENDENT-SEGMENTS";
private static final String TAG_MEDIA_DURATION = "#EXTINF";
private static final String TAG_MEDIA_SEQUENCE = "#EXT-X-MEDIA-SEQUENCE";
private static final String TAG_START = "#EXT-X-START";
private static final String TAG_ENDLIST = "#EXT-X-ENDLIST";
private static final String TAG_KEY = "#EXT-X-KEY";
private static final String TAG_SESSION_KEY = "#EXT-X-SESSION-KEY";
private static final String TAG_BYTERANGE = "#EXT-X-BYTERANGE";
private static final String TAG_GAP = "#EXT-X-GAP";
private static final String TYPE_AUDIO = "AUDIO";
private static final String TYPE_VIDEO = "VIDEO";
private static final String TYPE_SUBTITLES = "SUBTITLES";
private static final String TYPE_CLOSED_CAPTIONS = "CLOSED-CAPTIONS";
private static final String METHOD_NONE = "NONE";
private static final String METHOD_AES_128 = "AES-128";
private static final String METHOD_SAMPLE_AES = "SAMPLE-AES";
// Replaced by METHOD_SAMPLE_AES_CTR. Keep for backward compatibility.
private static final String METHOD_SAMPLE_AES_CENC = "SAMPLE-AES-CENC";
private static final String METHOD_SAMPLE_AES_CTR = "SAMPLE-AES-CTR";
private static final String KEYFORMAT_PLAYREADY = "com.microsoft.playready";
private static final String KEYFORMAT_IDENTITY = "identity";
private static final String KEYFORMAT_WIDEVINE_PSSH_BINARY =
"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";
private static final String KEYFORMAT_WIDEVINE_PSSH_JSON = "com.widevine";
private static final String BOOLEAN_TRUE = "YES";
private static final String BOOLEAN_FALSE = "NO";
private static final String ATTR_CLOSED_CAPTIONS_NONE = "CLOSED-CAPTIONS=NONE";
private static final Pattern REGEX_AVERAGE_BANDWIDTH =
Pattern.compile("AVERAGE-BANDWIDTH=(\\d+)\\b");
private static final Pattern REGEX_VIDEO = Pattern.compile("VIDEO=\"(.+?)\"");
private static final Pattern REGEX_AUDIO = Pattern.compile("AUDIO=\"(.+?)\"");
private static final Pattern REGEX_SUBTITLES = Pattern.compile("SUBTITLES=\"(.+?)\"");
private static final Pattern REGEX_CLOSED_CAPTIONS = Pattern.compile("CLOSED-CAPTIONS=\"(.+?)\"");
private static final Pattern REGEX_BANDWIDTH = Pattern.compile("[^-]BANDWIDTH=(\\d+)\\b");
private static final Pattern REGEX_CHANNELS = Pattern.compile("CHANNELS=\"(.+?)\"");
private static final Pattern REGEX_CODECS = Pattern.compile("CODECS=\"(.+?)\"");
private static final Pattern REGEX_RESOLUTION = Pattern.compile("RESOLUTION=(\\d+x\\d+)");
private static final Pattern REGEX_FRAME_RATE = Pattern.compile("FRAME-RATE=([\\d\\.]+)\\b");
private static final Pattern REGEX_TARGET_DURATION = Pattern.compile(TAG_TARGET_DURATION
+ ":(\\d+)\\b");
private static final Pattern REGEX_VERSION = Pattern.compile(TAG_VERSION + ":(\\d+)\\b");
private static final Pattern REGEX_PLAYLIST_TYPE = Pattern.compile(TAG_PLAYLIST_TYPE
+ ":(.+)\\b");
private static final Pattern REGEX_MEDIA_SEQUENCE = Pattern.compile(TAG_MEDIA_SEQUENCE
+ ":(\\d+)\\b");
private static final Pattern REGEX_MEDIA_DURATION = Pattern.compile(TAG_MEDIA_DURATION
+ ":([\\d\\.]+)\\b");
private static final Pattern REGEX_MEDIA_TITLE =
Pattern.compile(TAG_MEDIA_DURATION + ":[\\d\\.]+\\b,(.+)");
private static final Pattern REGEX_TIME_OFFSET = Pattern.compile("TIME-OFFSET=(-?[\\d\\.]+)\\b");
private static final Pattern REGEX_BYTERANGE = Pattern.compile(TAG_BYTERANGE
+ ":(\\d+(?:@\\d+)?)\\b");
private static final Pattern REGEX_ATTR_BYTERANGE =
Pattern.compile("BYTERANGE=\"(\\d+(?:@\\d+)?)\\b\"");
private static final Pattern REGEX_METHOD =
Pattern.compile(
"METHOD=("
+ METHOD_NONE
+ "|"
+ METHOD_AES_128
+ "|"
+ METHOD_SAMPLE_AES
+ "|"
+ METHOD_SAMPLE_AES_CENC
+ "|"
+ METHOD_SAMPLE_AES_CTR
+ ")"
+ "\\s*(?:,|$)");
private static final Pattern REGEX_KEYFORMAT = Pattern.compile("KEYFORMAT=\"(.+?)\"");
private static final Pattern REGEX_KEYFORMATVERSIONS =
Pattern.compile("KEYFORMATVERSIONS=\"(.+?)\"");
private static final Pattern REGEX_URI = Pattern.compile("URI=\"(.+?)\"");
private static final Pattern REGEX_IV = Pattern.compile("IV=([^,.*]+)");
private static final Pattern REGEX_TYPE = Pattern.compile("TYPE=(" + TYPE_AUDIO + "|" + TYPE_VIDEO
+ "|" + TYPE_SUBTITLES + "|" + TYPE_CLOSED_CAPTIONS + ")");
private static final Pattern REGEX_LANGUAGE = Pattern.compile("LANGUAGE=\"(.+?)\"");
private static final Pattern REGEX_NAME = Pattern.compile("NAME=\"(.+?)\"");
private static final Pattern REGEX_GROUP_ID = Pattern.compile("GROUP-ID=\"(.+?)\"");
private static final Pattern REGEX_CHARACTERISTICS = Pattern.compile("CHARACTERISTICS=\"(.+?)\"");
private static final Pattern REGEX_INSTREAM_ID =
Pattern.compile("INSTREAM-ID=\"((?:CC|SERVICE)\\d+)\"");
private static final Pattern REGEX_AUTOSELECT = compileBooleanAttrPattern("AUTOSELECT");
private static final Pattern REGEX_DEFAULT = compileBooleanAttrPattern("DEFAULT");
private static final Pattern REGEX_FORCED = compileBooleanAttrPattern("FORCED");
private static final Pattern REGEX_VALUE = Pattern.compile("VALUE=\"(.+?)\"");
private static final Pattern REGEX_IMPORT = Pattern.compile("IMPORT=\"(.+?)\"");
private static final Pattern REGEX_VARIABLE_REFERENCE =
Pattern.compile("\\{\\$([a-zA-Z0-9\\-_]+)\\}");
private final HlsMasterPlaylist masterPlaylist;
/**
* Creates an instance where media playlists are parsed without inheriting attributes from a
* master playlist.
*/
public HlsPlaylistParser() {
this(HlsMasterPlaylist.EMPTY);
}
/**
* Creates an instance where parsed media playlists inherit attributes from the given master
* playlist.
*
* @param masterPlaylist The master playlist from which media playlists will inherit attributes.
*/
public HlsPlaylistParser(HlsMasterPlaylist masterPlaylist) {
this.masterPlaylist = masterPlaylist;
}
@Override
public HlsPlaylist parse(Uri uri, InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
Queue<String> extraLines = new ArrayDeque<>();
String line;
try {
if (!checkPlaylistHeader(reader)) {
throw new UnrecognizedInputFormatException("Input does not start with the #EXTM3U header.",
uri);
}
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
// Do nothing.
} else if (line.startsWith(TAG_STREAM_INF)) {
extraLines.add(line);
return parseMasterPlaylist(new LineIterator(extraLines, reader), uri.toString());
} else if (line.startsWith(TAG_TARGET_DURATION)
|| line.startsWith(TAG_MEDIA_SEQUENCE)
|| line.startsWith(TAG_MEDIA_DURATION)
|| line.startsWith(TAG_KEY)
|| line.startsWith(TAG_BYTERANGE)
|| line.equals(TAG_DISCONTINUITY)
|| line.equals(TAG_DISCONTINUITY_SEQUENCE)
|| line.equals(TAG_ENDLIST)) {
extraLines.add(line);
return parseMediaPlaylist(
masterPlaylist, new LineIterator(extraLines, reader), uri.toString());
} else {
extraLines.add(line);
}
}
} finally {
Util.closeQuietly(reader);
}
throw new ParserException("Failed to parse the playlist, could not identify any tags.");
}
private static boolean checkPlaylistHeader(BufferedReader reader) throws IOException {
int last = reader.read();
if (last == 0xEF) {
if (reader.read() != 0xBB || reader.read() != 0xBF) {
return false;
}
// The playlist contains a Byte Order Mark, which gets discarded.
last = reader.read();
}
last = skipIgnorableWhitespace(reader, true, last);
int playlistHeaderLength = PLAYLIST_HEADER.length();
for (int i = 0; i < playlistHeaderLength; i++) {
if (last != PLAYLIST_HEADER.charAt(i)) {
return false;
}
last = reader.read();
}
last = skipIgnorableWhitespace(reader, false, last);
return Util.isLinebreak(last);
}
private static int skipIgnorableWhitespace(BufferedReader reader, boolean skipLinebreaks, int c)
throws IOException {
while (c != -1 && Character.isWhitespace(c) && (skipLinebreaks || !Util.isLinebreak(c))) {
c = reader.read();
}
return c;
}
private static HlsMasterPlaylist parseMasterPlaylist(LineIterator iterator, String baseUri)
throws IOException {
HashMap<Uri, ArrayList<VariantInfo>> urlToVariantInfos = new HashMap<>();
HashMap<String, String> variableDefinitions = new HashMap<>();
ArrayList<Variant> variants = new ArrayList<>();
ArrayList<Rendition> videos = new ArrayList<>();
ArrayList<Rendition> audios = new ArrayList<>();
ArrayList<Rendition> subtitles = new ArrayList<>();
ArrayList<Rendition> closedCaptions = new ArrayList<>();
ArrayList<String> mediaTags = new ArrayList<>();
ArrayList<DrmInitData> sessionKeyDrmInitData = new ArrayList<>();
ArrayList<String> tags = new ArrayList<>();
Format muxedAudioFormat = null;
List<Format> muxedCaptionFormats = null;
boolean noClosedCaptions = false;
boolean hasIndependentSegmentsTag = false;
String line;
while (iterator.hasNext()) {
line = iterator.next();
if (line.startsWith(TAG_PREFIX)) {
// We expose all tags through the playlist.
tags.add(line);
}
boolean isIFrameOnlyVariant = line.startsWith(TAG_I_FRAME_STREAM_INF);
if (line.startsWith(TAG_DEFINE)) {
variableDefinitions.put(
/* key= */ parseStringAttr(line, REGEX_NAME, variableDefinitions),
/* value= */ parseStringAttr(line, REGEX_VALUE, variableDefinitions));
} else if (line.equals(TAG_INDEPENDENT_SEGMENTS)) {
hasIndependentSegmentsTag = true;
} else if (line.startsWith(TAG_MEDIA)) {
// Media tags are parsed at the end to include codec information from #EXT-X-STREAM-INF
// tags.
mediaTags.add(line);
} else if (line.startsWith(TAG_SESSION_KEY)) {
String keyFormat =
parseOptionalStringAttr(line, REGEX_KEYFORMAT, KEYFORMAT_IDENTITY, variableDefinitions);
SchemeData schemeData = parseDrmSchemeData(line, keyFormat, variableDefinitions);
if (schemeData != null) {
String method = parseStringAttr(line, REGEX_METHOD, variableDefinitions);
String scheme = parseEncryptionScheme(method);
sessionKeyDrmInitData.add(new DrmInitData(scheme, schemeData));
}
} else if (line.startsWith(TAG_STREAM_INF) || isIFrameOnlyVariant) {
noClosedCaptions |= line.contains(ATTR_CLOSED_CAPTIONS_NONE);
int roleFlags = isIFrameOnlyVariant ? C.ROLE_FLAG_TRICK_PLAY : 0;
int peakBitrate = parseIntAttr(line, REGEX_BANDWIDTH);
int averageBitrate = parseOptionalIntAttr(line, REGEX_AVERAGE_BANDWIDTH, -1);
String codecs = parseOptionalStringAttr(line, REGEX_CODECS, variableDefinitions);
String resolutionString =
parseOptionalStringAttr(line, REGEX_RESOLUTION, variableDefinitions);
int width;
int height;
if (resolutionString != null) {
String[] widthAndHeight = resolutionString.split("x");
width = Integer.parseInt(widthAndHeight[0]);
height = Integer.parseInt(widthAndHeight[1]);
if (width <= 0 || height <= 0) {
// Resolution string is invalid.
width = Format.NO_VALUE;
height = Format.NO_VALUE;
}
} else {
width = Format.NO_VALUE;
height = Format.NO_VALUE;
}
float frameRate = Format.NO_VALUE;
String frameRateString =
parseOptionalStringAttr(line, REGEX_FRAME_RATE, variableDefinitions);
if (frameRateString != null) {
frameRate = Float.parseFloat(frameRateString);
}
String videoGroupId = parseOptionalStringAttr(line, REGEX_VIDEO, variableDefinitions);
String audioGroupId = parseOptionalStringAttr(line, REGEX_AUDIO, variableDefinitions);
String subtitlesGroupId =
parseOptionalStringAttr(line, REGEX_SUBTITLES, variableDefinitions);
String closedCaptionsGroupId =
parseOptionalStringAttr(line, REGEX_CLOSED_CAPTIONS, variableDefinitions);
Uri uri;
if (isIFrameOnlyVariant) {
uri =
UriUtil.resolveToUri(baseUri, parseStringAttr(line, REGEX_URI, variableDefinitions));
} else if (!iterator.hasNext()) {
throw new ParserException("#EXT-X-STREAM-INF must be followed by another line");
} else {
// The following line contains #EXT-X-STREAM-INF's URI.
line = replaceVariableReferences(iterator.next(), variableDefinitions);
uri = UriUtil.resolveToUri(baseUri, line);
}
Format format =
new Format.Builder()
.setId(variants.size())
.setContainerMimeType(MimeTypes.APPLICATION_M3U8)
.setCodecs(codecs)
.setAverageBitrate(averageBitrate)
.setPeakBitrate(peakBitrate)
.setWidth(width)
.setHeight(height)
.setFrameRate(frameRate)
.setRoleFlags(roleFlags)
.build();
Variant variant =
new Variant(
uri, format, videoGroupId, audioGroupId, subtitlesGroupId, closedCaptionsGroupId);
variants.add(variant);
@Nullable ArrayList<VariantInfo> variantInfosForUrl = urlToVariantInfos.get(uri);
if (variantInfosForUrl == null) {
variantInfosForUrl = new ArrayList<>();
urlToVariantInfos.put(uri, variantInfosForUrl);
}
variantInfosForUrl.add(
new VariantInfo(
averageBitrate,
peakBitrate,
videoGroupId,
audioGroupId,
subtitlesGroupId,
closedCaptionsGroupId));
}
}
// TODO: Don't deduplicate variants by URL.
ArrayList<Variant> deduplicatedVariants = new ArrayList<>();
HashSet<Uri> urlsInDeduplicatedVariants = new HashSet<>();
for (int i = 0; i < variants.size(); i++) {
Variant variant = variants.get(i);
if (urlsInDeduplicatedVariants.add(variant.url)) {
Assertions.checkState(variant.format.metadata == null);
HlsTrackMetadataEntry hlsMetadataEntry =
new HlsTrackMetadataEntry(
/* groupId= */ null,
/* name= */ null,
Assertions.checkNotNull(urlToVariantInfos.get(variant.url)));
Metadata metadata = new Metadata(hlsMetadataEntry);
Format format = variant.format.buildUpon().setMetadata(metadata).build();
deduplicatedVariants.add(variant.copyWithFormat(format));
}
}
for (int i = 0; i < mediaTags.size(); i++) {
line = mediaTags.get(i);
String groupId = parseStringAttr(line, REGEX_GROUP_ID, variableDefinitions);
String name = parseStringAttr(line, REGEX_NAME, variableDefinitions);
Format.Builder formatBuilder =
new Format.Builder()
.setId(groupId + ":" + name)
.setLabel(name)
.setContainerMimeType(MimeTypes.APPLICATION_M3U8)
.setSelectionFlags(parseSelectionFlags(line))
.setRoleFlags(parseRoleFlags(line, variableDefinitions))
.setLanguage(parseOptionalStringAttr(line, REGEX_LANGUAGE, variableDefinitions));
@Nullable String referenceUri = parseOptionalStringAttr(line, REGEX_URI, variableDefinitions);
@Nullable Uri uri = referenceUri == null ? null : UriUtil.resolveToUri(baseUri, referenceUri);
Metadata metadata =
new Metadata(new HlsTrackMetadataEntry(groupId, name, Collections.emptyList()));
switch (parseStringAttr(line, REGEX_TYPE, variableDefinitions)) {
case TYPE_VIDEO:
@Nullable Variant variant = getVariantWithVideoGroup(variants, groupId);
if (variant != null) {
Format variantFormat = variant.format;
@Nullable
String codecs = Util.getCodecsOfType(variantFormat.codecs, C.TRACK_TYPE_VIDEO);
formatBuilder
.setCodecs(codecs)
.setSampleMimeType(MimeTypes.getMediaMimeType(codecs))
.setWidth(variantFormat.width)
.setHeight(variantFormat.height)
.setFrameRate(variantFormat.frameRate);
}
if (uri == null) {
// TODO: Remove this case and add a Rendition with a null uri to videos.
} else {
formatBuilder.setMetadata(metadata);
videos.add(new Rendition(uri, formatBuilder.build(), groupId, name));
}
break;
case TYPE_AUDIO:
@Nullable String sampleMimeType = null;
variant = getVariantWithAudioGroup(variants, groupId);
if (variant != null) {
@Nullable
String codecs = Util.getCodecsOfType(variant.format.codecs, C.TRACK_TYPE_AUDIO);
formatBuilder.setCodecs(codecs);
sampleMimeType = MimeTypes.getMediaMimeType(codecs);
}
@Nullable
String channelsString =
parseOptionalStringAttr(line, REGEX_CHANNELS, variableDefinitions);
if (channelsString != null) {
int channelCount = Integer.parseInt(Util.splitAtFirst(channelsString, "/")[0]);
formatBuilder.setChannelCount(channelCount);
if (MimeTypes.AUDIO_E_AC3.equals(sampleMimeType) && channelsString.endsWith("/JOC")) {
sampleMimeType = MimeTypes.AUDIO_E_AC3_JOC;
}
}
formatBuilder.setSampleMimeType(sampleMimeType);
if (uri != null) {
formatBuilder.setMetadata(metadata);
audios.add(new Rendition(uri, formatBuilder.build(), groupId, name));
} else if (variant != null) {
// TODO: Remove muxedAudioFormat and add a Rendition with a null uri to audios.
muxedAudioFormat = formatBuilder.build();
}
break;
case TYPE_SUBTITLES:
sampleMimeType = null;
variant = getVariantWithSubtitleGroup(variants, groupId);
if (variant != null) {
@Nullable
String codecs = Util.getCodecsOfType(variant.format.codecs, C.TRACK_TYPE_TEXT);
formatBuilder.setCodecs(codecs);
sampleMimeType = MimeTypes.getMediaMimeType(codecs);
}
if (sampleMimeType == null) {
sampleMimeType = MimeTypes.TEXT_VTT;
}
formatBuilder.setSampleMimeType(sampleMimeType).setMetadata(metadata);
subtitles.add(new Rendition(uri, formatBuilder.build(), groupId, name));
break;
case TYPE_CLOSED_CAPTIONS:
String instreamId = parseStringAttr(line, REGEX_INSTREAM_ID, variableDefinitions);
int accessibilityChannel;
if (instreamId.startsWith("CC")) {
sampleMimeType = MimeTypes.APPLICATION_CEA608;
accessibilityChannel = Integer.parseInt(instreamId.substring(2));
} else /* starts with SERVICE */ {
sampleMimeType = MimeTypes.APPLICATION_CEA708;
accessibilityChannel = Integer.parseInt(instreamId.substring(7));
}
if (muxedCaptionFormats == null) {
muxedCaptionFormats = new ArrayList<>();
}
formatBuilder
.setSampleMimeType(sampleMimeType)
.setAccessibilityChannel(accessibilityChannel);
muxedCaptionFormats.add(formatBuilder.build());
// TODO: Remove muxedCaptionFormats and add a Rendition with a null uri to closedCaptions.
break;
default:
// Do nothing.
break;
}
}
if (noClosedCaptions) {
muxedCaptionFormats = Collections.emptyList();
}
return new HlsMasterPlaylist(
baseUri,
tags,
deduplicatedVariants,
videos,
audios,
subtitles,
closedCaptions,
muxedAudioFormat,
muxedCaptionFormats,
hasIndependentSegmentsTag,
variableDefinitions,
sessionKeyDrmInitData);
}
@Nullable
private static Variant getVariantWithAudioGroup(ArrayList<Variant> variants, String groupId) {
for (int i = 0; i < variants.size(); i++) {
Variant variant = variants.get(i);
if (groupId.equals(variant.audioGroupId)) {
return variant;
}
}
return null;
}
@Nullable
private static Variant getVariantWithVideoGroup(ArrayList<Variant> variants, String groupId) {
for (int i = 0; i < variants.size(); i++) {
Variant variant = variants.get(i);
if (groupId.equals(variant.videoGroupId)) {
return variant;
}
}
return null;
}
@Nullable
private static Variant getVariantWithSubtitleGroup(ArrayList<Variant> variants, String groupId) {
for (int i = 0; i < variants.size(); i++) {
Variant variant = variants.get(i);
if (groupId.equals(variant.subtitleGroupId)) {
return variant;
}
}
return null;
}
private static HlsMediaPlaylist parseMediaPlaylist(
HlsMasterPlaylist masterPlaylist, LineIterator iterator, String baseUri) throws IOException {
@HlsMediaPlaylist.PlaylistType int playlistType = HlsMediaPlaylist.PLAYLIST_TYPE_UNKNOWN;
long startOffsetUs = C.TIME_UNSET;
long mediaSequence = 0;
int version = 1; // Default version == 1.
long targetDurationUs = C.TIME_UNSET;
boolean hasIndependentSegmentsTag = masterPlaylist.hasIndependentSegments;
boolean hasEndTag = false;
@Nullable Segment initializationSegment = null;
HashMap<String, String> variableDefinitions = new HashMap<>();
HashMap<String, Segment> urlToInferredInitSegment = new HashMap<>();
List<Segment> segments = new ArrayList<>();
List<String> tags = new ArrayList<>();
long segmentDurationUs = 0;
String segmentTitle = "";
boolean hasDiscontinuitySequence = false;
int playlistDiscontinuitySequence = 0;
int relativeDiscontinuitySequence = 0;
long playlistStartTimeUs = 0;
long segmentStartTimeUs = 0;
long segmentByteRangeOffset = 0;
long segmentByteRangeLength = C.LENGTH_UNSET;
boolean isIFrameOnly = false;
long segmentMediaSequence = 0;
boolean hasGapTag = false;
DrmInitData playlistProtectionSchemes = null;
String fullSegmentEncryptionKeyUri = null;
String fullSegmentEncryptionIV = null;
TreeMap<String, SchemeData> currentSchemeDatas = new TreeMap<>();
String encryptionScheme = null;
DrmInitData cachedDrmInitData = null;
String line;
while (iterator.hasNext()) {
line = iterator.next();
if (line.startsWith(TAG_PREFIX)) {
// We expose all tags through the playlist.
tags.add(line);
}
if (line.startsWith(TAG_PLAYLIST_TYPE)) {
String playlistTypeString = parseStringAttr(line, REGEX_PLAYLIST_TYPE, variableDefinitions);
if ("VOD".equals(playlistTypeString)) {
playlistType = HlsMediaPlaylist.PLAYLIST_TYPE_VOD;
} else if ("EVENT".equals(playlistTypeString)) {
playlistType = HlsMediaPlaylist.PLAYLIST_TYPE_EVENT;
}
} else if (line.equals(TAG_IFRAME)) {
isIFrameOnly = true;
} else if (line.startsWith(TAG_START)) {
startOffsetUs = (long) (parseDoubleAttr(line, REGEX_TIME_OFFSET) * C.MICROS_PER_SECOND);
} else if (line.startsWith(TAG_INIT_SEGMENT)) {
String uri = parseStringAttr(line, REGEX_URI, variableDefinitions);
String byteRange = parseOptionalStringAttr(line, REGEX_ATTR_BYTERANGE, variableDefinitions);
if (byteRange != null) {
String[] splitByteRange = byteRange.split("@");
segmentByteRangeLength = Long.parseLong(splitByteRange[0]);
if (splitByteRange.length > 1) {
segmentByteRangeOffset = Long.parseLong(splitByteRange[1]);
}
}
if (fullSegmentEncryptionKeyUri != null && fullSegmentEncryptionIV == null) {
// See RFC 8216, Section 4.3.2.5.
throw new ParserException(
"The encryption IV attribute must be present when an initialization segment is "
+ "encrypted with METHOD=AES-128.");
}
initializationSegment =
new Segment(
uri,
segmentByteRangeOffset,
segmentByteRangeLength,
fullSegmentEncryptionKeyUri,
fullSegmentEncryptionIV);
segmentByteRangeOffset = 0;
segmentByteRangeLength = C.LENGTH_UNSET;
} else if (line.startsWith(TAG_TARGET_DURATION)) {
targetDurationUs = parseIntAttr(line, REGEX_TARGET_DURATION) * C.MICROS_PER_SECOND;
} else if (line.startsWith(TAG_MEDIA_SEQUENCE)) {
mediaSequence = parseLongAttr(line, REGEX_MEDIA_SEQUENCE);
segmentMediaSequence = mediaSequence;
} else if (line.startsWith(TAG_VERSION)) {
version = parseIntAttr(line, REGEX_VERSION);
} else if (line.startsWith(TAG_DEFINE)) {
String importName = parseOptionalStringAttr(line, REGEX_IMPORT, variableDefinitions);
if (importName != null) {
String value = masterPlaylist.variableDefinitions.get(importName);
if (value != null) {
variableDefinitions.put(importName, value);
} else {
// The master playlist does not declare the imported variable. Ignore.
}
} else {
variableDefinitions.put(
parseStringAttr(line, REGEX_NAME, variableDefinitions),
parseStringAttr(line, REGEX_VALUE, variableDefinitions));
}
} else if (line.startsWith(TAG_MEDIA_DURATION)) {
segmentDurationUs =
(long) (parseDoubleAttr(line, REGEX_MEDIA_DURATION) * C.MICROS_PER_SECOND);
segmentTitle = parseOptionalStringAttr(line, REGEX_MEDIA_TITLE, "", variableDefinitions);
} else if (line.startsWith(TAG_KEY)) {
String method = parseStringAttr(line, REGEX_METHOD, variableDefinitions);
String keyFormat =
parseOptionalStringAttr(line, REGEX_KEYFORMAT, KEYFORMAT_IDENTITY, variableDefinitions);
fullSegmentEncryptionKeyUri = null;
fullSegmentEncryptionIV = null;
if (METHOD_NONE.equals(method)) {
currentSchemeDatas.clear();
cachedDrmInitData = null;
} else /* !METHOD_NONE.equals(method) */ {
fullSegmentEncryptionIV = parseOptionalStringAttr(line, REGEX_IV, variableDefinitions);
if (KEYFORMAT_IDENTITY.equals(keyFormat)) {
if (METHOD_AES_128.equals(method)) {
// The segment is fully encrypted using an identity key.
fullSegmentEncryptionKeyUri = parseStringAttr(line, REGEX_URI, variableDefinitions);
} else {
// Do nothing. Samples are encrypted using an identity key, but this is not supported.
// Hopefully, a traditional DRM alternative is also provided.
}
} else {
if (encryptionScheme == null) {
encryptionScheme = parseEncryptionScheme(method);
}
SchemeData schemeData = parseDrmSchemeData(line, keyFormat, variableDefinitions);
if (schemeData != null) {
cachedDrmInitData = null;
currentSchemeDatas.put(keyFormat, schemeData);
}
}
}
} else if (line.startsWith(TAG_BYTERANGE)) {
String byteRange = parseStringAttr(line, REGEX_BYTERANGE, variableDefinitions);
String[] splitByteRange = byteRange.split("@");
segmentByteRangeLength = Long.parseLong(splitByteRange[0]);
if (splitByteRange.length > 1) {
segmentByteRangeOffset = Long.parseLong(splitByteRange[1]);
}
} else if (line.startsWith(TAG_DISCONTINUITY_SEQUENCE)) {
hasDiscontinuitySequence = true;
playlistDiscontinuitySequence = Integer.parseInt(line.substring(line.indexOf(':') + 1));
} else if (line.equals(TAG_DISCONTINUITY)) {
relativeDiscontinuitySequence++;
} else if (line.startsWith(TAG_PROGRAM_DATE_TIME)) {
if (playlistStartTimeUs == 0) {
long programDatetimeUs =
C.msToUs(Util.parseXsDateTime(line.substring(line.indexOf(':') + 1)));
playlistStartTimeUs = programDatetimeUs - segmentStartTimeUs;
}
} else if (line.equals(TAG_GAP)) {
hasGapTag = true;
} else if (line.equals(TAG_INDEPENDENT_SEGMENTS)) {
hasIndependentSegmentsTag = true;
} else if (line.equals(TAG_ENDLIST)) {
hasEndTag = true;
} else if (!line.startsWith("#")) {
String segmentEncryptionIV;
if (fullSegmentEncryptionKeyUri == null) {
segmentEncryptionIV = null;
} else if (fullSegmentEncryptionIV != null) {
segmentEncryptionIV = fullSegmentEncryptionIV;
} else {
segmentEncryptionIV = Long.toHexString(segmentMediaSequence);
}
segmentMediaSequence++;
String segmentUri = replaceVariableReferences(line, variableDefinitions);
@Nullable Segment inferredInitSegment = urlToInferredInitSegment.get(segmentUri);
if (segmentByteRangeLength == C.LENGTH_UNSET) {
// The segment is not byte range defined.
segmentByteRangeOffset = 0;
} else if (isIFrameOnly && initializationSegment == null && inferredInitSegment == null) {
// The segment is a resource byte range without an initialization segment.
// As per RFC 8216, Section 4.3.3.6, we assume the initialization section exists in the
// bytes preceding the first segment in this segment's URL.
// We assume the implicit initialization segment is unencrypted, since there's no way for
// the playlist to provide an initialization vector for it.
inferredInitSegment =
new Segment(
segmentUri,
/* byteRangeOffset= */ 0,
segmentByteRangeOffset,
/* fullSegmentEncryptionKeyUri= */ null,
/* encryptionIV= */ null);
urlToInferredInitSegment.put(segmentUri, inferredInitSegment);
}
if (cachedDrmInitData == null && !currentSchemeDatas.isEmpty()) {
SchemeData[] schemeDatas = currentSchemeDatas.values().toArray(new SchemeData[0]);
cachedDrmInitData = new DrmInitData(encryptionScheme, schemeDatas);
if (playlistProtectionSchemes == null) {
SchemeData[] playlistSchemeDatas = new SchemeData[schemeDatas.length];
for (int i = 0; i < schemeDatas.length; i++) {
playlistSchemeDatas[i] = schemeDatas[i].copyWithData(null);
}
playlistProtectionSchemes = new DrmInitData(encryptionScheme, playlistSchemeDatas);
}
}
segments.add(
new Segment(
segmentUri,
initializationSegment != null ? initializationSegment : inferredInitSegment,
segmentTitle,
segmentDurationUs,
relativeDiscontinuitySequence,
segmentStartTimeUs,
cachedDrmInitData,
fullSegmentEncryptionKeyUri,
segmentEncryptionIV,
segmentByteRangeOffset,
segmentByteRangeLength,
hasGapTag));
segmentStartTimeUs += segmentDurationUs;
segmentDurationUs = 0;
segmentTitle = "";
if (segmentByteRangeLength != C.LENGTH_UNSET) {
segmentByteRangeOffset += segmentByteRangeLength;
}
segmentByteRangeLength = C.LENGTH_UNSET;
hasGapTag = false;
}
}
return new HlsMediaPlaylist(
playlistType,
baseUri,
tags,
startOffsetUs,
playlistStartTimeUs,
hasDiscontinuitySequence,
playlistDiscontinuitySequence,
mediaSequence,
version,
targetDurationUs,
hasIndependentSegmentsTag,
hasEndTag,
/* hasProgramDateTime= */ playlistStartTimeUs != 0,
playlistProtectionSchemes,
segments);
}
@C.SelectionFlags
private static int parseSelectionFlags(String line) {
int flags = 0;
if (parseOptionalBooleanAttribute(line, REGEX_DEFAULT, false)) {
flags |= C.SELECTION_FLAG_DEFAULT;
}
if (parseOptionalBooleanAttribute(line, REGEX_FORCED, false)) {
flags |= C.SELECTION_FLAG_FORCED;
}
if (parseOptionalBooleanAttribute(line, REGEX_AUTOSELECT, false)) {
flags |= C.SELECTION_FLAG_AUTOSELECT;
}
return flags;
}
@C.RoleFlags
private static int parseRoleFlags(String line, Map<String, String> variableDefinitions) {
String concatenatedCharacteristics =
parseOptionalStringAttr(line, REGEX_CHARACTERISTICS, variableDefinitions);
if (TextUtils.isEmpty(concatenatedCharacteristics)) {
return 0;
}
String[] characteristics = Util.split(concatenatedCharacteristics, ",");
@C.RoleFlags int roleFlags = 0;
if (Util.contains(characteristics, "public.accessibility.describes-video")) {
roleFlags |= C.ROLE_FLAG_DESCRIBES_VIDEO;
}
if (Util.contains(characteristics, "public.accessibility.transcribes-spoken-dialog")) {
roleFlags |= C.ROLE_FLAG_TRANSCRIBES_DIALOG;
}
if (Util.contains(characteristics, "public.accessibility.describes-music-and-sound")) {
roleFlags |= C.ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND;
}
if (Util.contains(characteristics, "public.easy-to-read")) {
roleFlags |= C.ROLE_FLAG_EASY_TO_READ;
}
return roleFlags;
}
@Nullable
private static SchemeData parseDrmSchemeData(
String line, String keyFormat, Map<String, String> variableDefinitions)
throws ParserException {
String keyFormatVersions =
parseOptionalStringAttr(line, REGEX_KEYFORMATVERSIONS, "1", variableDefinitions);
if (KEYFORMAT_WIDEVINE_PSSH_BINARY.equals(keyFormat)) {
String uriString = parseStringAttr(line, REGEX_URI, variableDefinitions);
return new SchemeData(
C.WIDEVINE_UUID,
MimeTypes.VIDEO_MP4,
Base64.decode(uriString.substring(uriString.indexOf(',')), Base64.DEFAULT));
} else if (KEYFORMAT_WIDEVINE_PSSH_JSON.equals(keyFormat)) {
return new SchemeData(C.WIDEVINE_UUID, "hls", Util.getUtf8Bytes(line));
} else if (KEYFORMAT_PLAYREADY.equals(keyFormat) && "1".equals(keyFormatVersions)) {
String uriString = parseStringAttr(line, REGEX_URI, variableDefinitions);
byte[] data = Base64.decode(uriString.substring(uriString.indexOf(',')), Base64.DEFAULT);
byte[] psshData = PsshAtomUtil.buildPsshAtom(C.PLAYREADY_UUID, data);
return new SchemeData(C.PLAYREADY_UUID, MimeTypes.VIDEO_MP4, psshData);
}
return null;
}
private static String parseEncryptionScheme(String method) {
return METHOD_SAMPLE_AES_CENC.equals(method) || METHOD_SAMPLE_AES_CTR.equals(method)
? C.CENC_TYPE_cenc
: C.CENC_TYPE_cbcs;
}
private static int parseIntAttr(String line, Pattern pattern) throws ParserException {
return Integer.parseInt(parseStringAttr(line, pattern, Collections.emptyMap()));
}
private static int parseOptionalIntAttr(String line, Pattern pattern, int defaultValue) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return Integer.parseInt(Assertions.checkNotNull(matcher.group(1)));
}
return defaultValue;
}
private static long parseLongAttr(String line, Pattern pattern) throws ParserException {
return Long.parseLong(parseStringAttr(line, pattern, Collections.emptyMap()));
}
private static double parseDoubleAttr(String line, Pattern pattern) throws ParserException {
return Double.parseDouble(parseStringAttr(line, pattern, Collections.emptyMap()));
}
private static String parseStringAttr(
String line, Pattern pattern, Map<String, String> variableDefinitions)
throws ParserException {
String value = parseOptionalStringAttr(line, pattern, variableDefinitions);
if (value != null) {
return value;
} else {
throw new ParserException("Couldn't match " + pattern.pattern() + " in " + line);
}
}
private static @Nullable String parseOptionalStringAttr(
String line, Pattern pattern, Map<String, String> variableDefinitions) {
return parseOptionalStringAttr(line, pattern, null, variableDefinitions);
}
private static @PolyNull String parseOptionalStringAttr(
String line,
Pattern pattern,
@PolyNull String defaultValue,
Map<String, String> variableDefinitions) {
Matcher matcher = pattern.matcher(line);
@PolyNull
String value = matcher.find() ? Assertions.checkNotNull(matcher.group(1)) : defaultValue;
return variableDefinitions.isEmpty() || value == null
? value
: replaceVariableReferences(value, variableDefinitions);
}
private static String replaceVariableReferences(
String string, Map<String, String> variableDefinitions) {
Matcher matcher = REGEX_VARIABLE_REFERENCE.matcher(string);
// TODO: Replace StringBuffer with StringBuilder once Java 9 is available.
StringBuffer stringWithReplacements = new StringBuffer();
while (matcher.find()) {
String groupName = matcher.group(1);
if (variableDefinitions.containsKey(groupName)) {
matcher.appendReplacement(
stringWithReplacements, Matcher.quoteReplacement(variableDefinitions.get(groupName)));
} else {
// The variable is not defined. The value is ignored.
}
}
matcher.appendTail(stringWithReplacements);
return stringWithReplacements.toString();
}
private static boolean parseOptionalBooleanAttribute(
String line, Pattern pattern, boolean defaultValue) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return BOOLEAN_TRUE.equals(matcher.group(1));
}
return defaultValue;
}
private static Pattern compileBooleanAttrPattern(String attribute) {
return Pattern.compile(attribute + "=(" + BOOLEAN_FALSE + "|" + BOOLEAN_TRUE + ")");
}
private static class LineIterator {
private final BufferedReader reader;
private final Queue<String> extraLines;
@Nullable private String next;
public LineIterator(Queue<String> extraLines, BufferedReader reader) {
this.extraLines = extraLines;
this.reader = reader;
}
@EnsuresNonNullIf(expression = "next", result = true)
public boolean hasNext() throws IOException {
if (next != null) {
return true;
}
if (!extraLines.isEmpty()) {
next = Assertions.checkNotNull(extraLines.poll());
return true;
}
while ((next = reader.readLine()) != null) {
next = next.trim();
if (!next.isEmpty()) {
return true;
}
}
return false;
}
/** Return the next line, or throw {@link NoSuchElementException} if none. */
public String next() throws IOException {
if (hasNext()) {
String result = next;
next = null;
return result;
} else {
throw new NoSuchElementException();
}
}
}
}
| library/hls/src/main/java/com/google/android/exoplayer2/source/hls/playlist/HlsPlaylistParser.java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.source.hls.playlist;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.drm.DrmInitData.SchemeData;
import com.google.android.exoplayer2.extractor.mp4.PsshAtomUtil;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.source.UnrecognizedInputFormatException;
import com.google.android.exoplayer2.source.hls.HlsTrackMetadataEntry;
import com.google.android.exoplayer2.source.hls.HlsTrackMetadataEntry.VariantInfo;
import com.google.android.exoplayer2.source.hls.playlist.HlsMasterPlaylist.Rendition;
import com.google.android.exoplayer2.source.hls.playlist.HlsMasterPlaylist.Variant;
import com.google.android.exoplayer2.source.hls.playlist.HlsMediaPlaylist.Segment;
import com.google.android.exoplayer2.upstream.ParsingLoadable;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.UriUtil;
import com.google.android.exoplayer2.util.Util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
import org.checkerframework.checker.nullness.qual.PolyNull;
/**
* HLS playlists parsing logic.
*/
public final class HlsPlaylistParser implements ParsingLoadable.Parser<HlsPlaylist> {
private static final String PLAYLIST_HEADER = "#EXTM3U";
private static final String TAG_PREFIX = "#EXT";
private static final String TAG_VERSION = "#EXT-X-VERSION";
private static final String TAG_PLAYLIST_TYPE = "#EXT-X-PLAYLIST-TYPE";
private static final String TAG_DEFINE = "#EXT-X-DEFINE";
private static final String TAG_STREAM_INF = "#EXT-X-STREAM-INF";
private static final String TAG_I_FRAME_STREAM_INF = "#EXT-X-I-FRAME-STREAM-INF";
private static final String TAG_IFRAME = "#EXT-X-I-FRAMES-ONLY";
private static final String TAG_MEDIA = "#EXT-X-MEDIA";
private static final String TAG_TARGET_DURATION = "#EXT-X-TARGETDURATION";
private static final String TAG_DISCONTINUITY = "#EXT-X-DISCONTINUITY";
private static final String TAG_DISCONTINUITY_SEQUENCE = "#EXT-X-DISCONTINUITY-SEQUENCE";
private static final String TAG_PROGRAM_DATE_TIME = "#EXT-X-PROGRAM-DATE-TIME";
private static final String TAG_INIT_SEGMENT = "#EXT-X-MAP";
private static final String TAG_INDEPENDENT_SEGMENTS = "#EXT-X-INDEPENDENT-SEGMENTS";
private static final String TAG_MEDIA_DURATION = "#EXTINF";
private static final String TAG_MEDIA_SEQUENCE = "#EXT-X-MEDIA-SEQUENCE";
private static final String TAG_START = "#EXT-X-START";
private static final String TAG_ENDLIST = "#EXT-X-ENDLIST";
private static final String TAG_KEY = "#EXT-X-KEY";
private static final String TAG_SESSION_KEY = "#EXT-X-SESSION-KEY";
private static final String TAG_BYTERANGE = "#EXT-X-BYTERANGE";
private static final String TAG_GAP = "#EXT-X-GAP";
private static final String TYPE_AUDIO = "AUDIO";
private static final String TYPE_VIDEO = "VIDEO";
private static final String TYPE_SUBTITLES = "SUBTITLES";
private static final String TYPE_CLOSED_CAPTIONS = "CLOSED-CAPTIONS";
private static final String METHOD_NONE = "NONE";
private static final String METHOD_AES_128 = "AES-128";
private static final String METHOD_SAMPLE_AES = "SAMPLE-AES";
// Replaced by METHOD_SAMPLE_AES_CTR. Keep for backward compatibility.
private static final String METHOD_SAMPLE_AES_CENC = "SAMPLE-AES-CENC";
private static final String METHOD_SAMPLE_AES_CTR = "SAMPLE-AES-CTR";
private static final String KEYFORMAT_PLAYREADY = "com.microsoft.playready";
private static final String KEYFORMAT_IDENTITY = "identity";
private static final String KEYFORMAT_WIDEVINE_PSSH_BINARY =
"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";
private static final String KEYFORMAT_WIDEVINE_PSSH_JSON = "com.widevine";
private static final String BOOLEAN_TRUE = "YES";
private static final String BOOLEAN_FALSE = "NO";
private static final String ATTR_CLOSED_CAPTIONS_NONE = "CLOSED-CAPTIONS=NONE";
private static final Pattern REGEX_AVERAGE_BANDWIDTH =
Pattern.compile("AVERAGE-BANDWIDTH=(\\d+)\\b");
private static final Pattern REGEX_VIDEO = Pattern.compile("VIDEO=\"(.+?)\"");
private static final Pattern REGEX_AUDIO = Pattern.compile("AUDIO=\"(.+?)\"");
private static final Pattern REGEX_SUBTITLES = Pattern.compile("SUBTITLES=\"(.+?)\"");
private static final Pattern REGEX_CLOSED_CAPTIONS = Pattern.compile("CLOSED-CAPTIONS=\"(.+?)\"");
private static final Pattern REGEX_BANDWIDTH = Pattern.compile("[^-]BANDWIDTH=(\\d+)\\b");
private static final Pattern REGEX_CHANNELS = Pattern.compile("CHANNELS=\"(.+?)\"");
private static final Pattern REGEX_CODECS = Pattern.compile("CODECS=\"(.+?)\"");
private static final Pattern REGEX_RESOLUTION = Pattern.compile("RESOLUTION=(\\d+x\\d+)");
private static final Pattern REGEX_FRAME_RATE = Pattern.compile("FRAME-RATE=([\\d\\.]+)\\b");
private static final Pattern REGEX_TARGET_DURATION = Pattern.compile(TAG_TARGET_DURATION
+ ":(\\d+)\\b");
private static final Pattern REGEX_VERSION = Pattern.compile(TAG_VERSION + ":(\\d+)\\b");
private static final Pattern REGEX_PLAYLIST_TYPE = Pattern.compile(TAG_PLAYLIST_TYPE
+ ":(.+)\\b");
private static final Pattern REGEX_MEDIA_SEQUENCE = Pattern.compile(TAG_MEDIA_SEQUENCE
+ ":(\\d+)\\b");
private static final Pattern REGEX_MEDIA_DURATION = Pattern.compile(TAG_MEDIA_DURATION
+ ":([\\d\\.]+)\\b");
private static final Pattern REGEX_MEDIA_TITLE =
Pattern.compile(TAG_MEDIA_DURATION + ":[\\d\\.]+\\b,(.+)");
private static final Pattern REGEX_TIME_OFFSET = Pattern.compile("TIME-OFFSET=(-?[\\d\\.]+)\\b");
private static final Pattern REGEX_BYTERANGE = Pattern.compile(TAG_BYTERANGE
+ ":(\\d+(?:@\\d+)?)\\b");
private static final Pattern REGEX_ATTR_BYTERANGE =
Pattern.compile("BYTERANGE=\"(\\d+(?:@\\d+)?)\\b\"");
private static final Pattern REGEX_METHOD =
Pattern.compile(
"METHOD=("
+ METHOD_NONE
+ "|"
+ METHOD_AES_128
+ "|"
+ METHOD_SAMPLE_AES
+ "|"
+ METHOD_SAMPLE_AES_CENC
+ "|"
+ METHOD_SAMPLE_AES_CTR
+ ")"
+ "\\s*(?:,|$)");
private static final Pattern REGEX_KEYFORMAT = Pattern.compile("KEYFORMAT=\"(.+?)\"");
private static final Pattern REGEX_KEYFORMATVERSIONS =
Pattern.compile("KEYFORMATVERSIONS=\"(.+?)\"");
private static final Pattern REGEX_URI = Pattern.compile("URI=\"(.+?)\"");
private static final Pattern REGEX_IV = Pattern.compile("IV=([^,.*]+)");
private static final Pattern REGEX_TYPE = Pattern.compile("TYPE=(" + TYPE_AUDIO + "|" + TYPE_VIDEO
+ "|" + TYPE_SUBTITLES + "|" + TYPE_CLOSED_CAPTIONS + ")");
private static final Pattern REGEX_LANGUAGE = Pattern.compile("LANGUAGE=\"(.+?)\"");
private static final Pattern REGEX_NAME = Pattern.compile("NAME=\"(.+?)\"");
private static final Pattern REGEX_GROUP_ID = Pattern.compile("GROUP-ID=\"(.+?)\"");
private static final Pattern REGEX_CHARACTERISTICS = Pattern.compile("CHARACTERISTICS=\"(.+?)\"");
private static final Pattern REGEX_INSTREAM_ID =
Pattern.compile("INSTREAM-ID=\"((?:CC|SERVICE)\\d+)\"");
private static final Pattern REGEX_AUTOSELECT = compileBooleanAttrPattern("AUTOSELECT");
private static final Pattern REGEX_DEFAULT = compileBooleanAttrPattern("DEFAULT");
private static final Pattern REGEX_FORCED = compileBooleanAttrPattern("FORCED");
private static final Pattern REGEX_VALUE = Pattern.compile("VALUE=\"(.+?)\"");
private static final Pattern REGEX_IMPORT = Pattern.compile("IMPORT=\"(.+?)\"");
private static final Pattern REGEX_VARIABLE_REFERENCE =
Pattern.compile("\\{\\$([a-zA-Z0-9\\-_]+)\\}");
private final HlsMasterPlaylist masterPlaylist;
/**
* Creates an instance where media playlists are parsed without inheriting attributes from a
* master playlist.
*/
public HlsPlaylistParser() {
this(HlsMasterPlaylist.EMPTY);
}
/**
* Creates an instance where parsed media playlists inherit attributes from the given master
* playlist.
*
* @param masterPlaylist The master playlist from which media playlists will inherit attributes.
*/
public HlsPlaylistParser(HlsMasterPlaylist masterPlaylist) {
this.masterPlaylist = masterPlaylist;
}
@Override
public HlsPlaylist parse(Uri uri, InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
Queue<String> extraLines = new ArrayDeque<>();
String line;
try {
if (!checkPlaylistHeader(reader)) {
throw new UnrecognizedInputFormatException("Input does not start with the #EXTM3U header.",
uri);
}
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
// Do nothing.
} else if (line.startsWith(TAG_STREAM_INF)) {
extraLines.add(line);
return parseMasterPlaylist(new LineIterator(extraLines, reader), uri.toString());
} else if (line.startsWith(TAG_TARGET_DURATION)
|| line.startsWith(TAG_MEDIA_SEQUENCE)
|| line.startsWith(TAG_MEDIA_DURATION)
|| line.startsWith(TAG_KEY)
|| line.startsWith(TAG_BYTERANGE)
|| line.equals(TAG_DISCONTINUITY)
|| line.equals(TAG_DISCONTINUITY_SEQUENCE)
|| line.equals(TAG_ENDLIST)) {
extraLines.add(line);
return parseMediaPlaylist(
masterPlaylist, new LineIterator(extraLines, reader), uri.toString());
} else {
extraLines.add(line);
}
}
} finally {
Util.closeQuietly(reader);
}
throw new ParserException("Failed to parse the playlist, could not identify any tags.");
}
private static boolean checkPlaylistHeader(BufferedReader reader) throws IOException {
int last = reader.read();
if (last == 0xEF) {
if (reader.read() != 0xBB || reader.read() != 0xBF) {
return false;
}
// The playlist contains a Byte Order Mark, which gets discarded.
last = reader.read();
}
last = skipIgnorableWhitespace(reader, true, last);
int playlistHeaderLength = PLAYLIST_HEADER.length();
for (int i = 0; i < playlistHeaderLength; i++) {
if (last != PLAYLIST_HEADER.charAt(i)) {
return false;
}
last = reader.read();
}
last = skipIgnorableWhitespace(reader, false, last);
return Util.isLinebreak(last);
}
private static int skipIgnorableWhitespace(BufferedReader reader, boolean skipLinebreaks, int c)
throws IOException {
while (c != -1 && Character.isWhitespace(c) && (skipLinebreaks || !Util.isLinebreak(c))) {
c = reader.read();
}
return c;
}
private static HlsMasterPlaylist parseMasterPlaylist(LineIterator iterator, String baseUri)
throws IOException {
HashMap<Uri, ArrayList<VariantInfo>> urlToVariantInfos = new HashMap<>();
HashMap<String, String> variableDefinitions = new HashMap<>();
ArrayList<Variant> variants = new ArrayList<>();
ArrayList<Rendition> videos = new ArrayList<>();
ArrayList<Rendition> audios = new ArrayList<>();
ArrayList<Rendition> subtitles = new ArrayList<>();
ArrayList<Rendition> closedCaptions = new ArrayList<>();
ArrayList<String> mediaTags = new ArrayList<>();
ArrayList<DrmInitData> sessionKeyDrmInitData = new ArrayList<>();
ArrayList<String> tags = new ArrayList<>();
Format muxedAudioFormat = null;
List<Format> muxedCaptionFormats = null;
boolean noClosedCaptions = false;
boolean hasIndependentSegmentsTag = false;
String line;
while (iterator.hasNext()) {
line = iterator.next();
if (line.startsWith(TAG_PREFIX)) {
// We expose all tags through the playlist.
tags.add(line);
}
boolean isIFrameOnlyVariant = line.startsWith(TAG_I_FRAME_STREAM_INF);
if (line.startsWith(TAG_DEFINE)) {
variableDefinitions.put(
/* key= */ parseStringAttr(line, REGEX_NAME, variableDefinitions),
/* value= */ parseStringAttr(line, REGEX_VALUE, variableDefinitions));
} else if (line.equals(TAG_INDEPENDENT_SEGMENTS)) {
hasIndependentSegmentsTag = true;
} else if (line.startsWith(TAG_MEDIA)) {
// Media tags are parsed at the end to include codec information from #EXT-X-STREAM-INF
// tags.
mediaTags.add(line);
} else if (line.startsWith(TAG_SESSION_KEY)) {
String keyFormat =
parseOptionalStringAttr(line, REGEX_KEYFORMAT, KEYFORMAT_IDENTITY, variableDefinitions);
SchemeData schemeData = parseDrmSchemeData(line, keyFormat, variableDefinitions);
if (schemeData != null) {
String method = parseStringAttr(line, REGEX_METHOD, variableDefinitions);
String scheme = parseEncryptionScheme(method);
sessionKeyDrmInitData.add(new DrmInitData(scheme, schemeData));
}
} else if (line.startsWith(TAG_STREAM_INF) || isIFrameOnlyVariant) {
noClosedCaptions |= line.contains(ATTR_CLOSED_CAPTIONS_NONE);
int roleFlags = isIFrameOnlyVariant ? C.ROLE_FLAG_TRICK_PLAY : 0;
int peakBitrate = parseIntAttr(line, REGEX_BANDWIDTH);
int averageBitrate = parseOptionalIntAttr(line, REGEX_AVERAGE_BANDWIDTH, -1);
String codecs = parseOptionalStringAttr(line, REGEX_CODECS, variableDefinitions);
String resolutionString =
parseOptionalStringAttr(line, REGEX_RESOLUTION, variableDefinitions);
int width;
int height;
if (resolutionString != null) {
String[] widthAndHeight = resolutionString.split("x");
width = Integer.parseInt(widthAndHeight[0]);
height = Integer.parseInt(widthAndHeight[1]);
if (width <= 0 || height <= 0) {
// Resolution string is invalid.
width = Format.NO_VALUE;
height = Format.NO_VALUE;
}
} else {
width = Format.NO_VALUE;
height = Format.NO_VALUE;
}
float frameRate = Format.NO_VALUE;
String frameRateString =
parseOptionalStringAttr(line, REGEX_FRAME_RATE, variableDefinitions);
if (frameRateString != null) {
frameRate = Float.parseFloat(frameRateString);
}
String videoGroupId = parseOptionalStringAttr(line, REGEX_VIDEO, variableDefinitions);
String audioGroupId = parseOptionalStringAttr(line, REGEX_AUDIO, variableDefinitions);
String subtitlesGroupId =
parseOptionalStringAttr(line, REGEX_SUBTITLES, variableDefinitions);
String closedCaptionsGroupId =
parseOptionalStringAttr(line, REGEX_CLOSED_CAPTIONS, variableDefinitions);
Uri uri;
if (isIFrameOnlyVariant) {
uri =
UriUtil.resolveToUri(baseUri, parseStringAttr(line, REGEX_URI, variableDefinitions));
} else if (!iterator.hasNext()) {
throw new ParserException("#EXT-X-STREAM-INF must be followed by another line");
} else {
// The following line contains #EXT-X-STREAM-INF's URI.
line = replaceVariableReferences(iterator.next(), variableDefinitions);
uri = UriUtil.resolveToUri(baseUri, line);
}
Format format =
new Format.Builder()
.setId(variants.size())
.setContainerMimeType(MimeTypes.APPLICATION_M3U8)
.setCodecs(codecs)
.setAverageBitrate(averageBitrate)
.setPeakBitrate(peakBitrate)
.setWidth(width)
.setHeight(height)
.setFrameRate(frameRate)
.setRoleFlags(roleFlags)
.build();
Variant variant =
new Variant(
uri, format, videoGroupId, audioGroupId, subtitlesGroupId, closedCaptionsGroupId);
variants.add(variant);
@Nullable ArrayList<VariantInfo> variantInfosForUrl = urlToVariantInfos.get(uri);
if (variantInfosForUrl == null) {
variantInfosForUrl = new ArrayList<>();
urlToVariantInfos.put(uri, variantInfosForUrl);
}
variantInfosForUrl.add(
new VariantInfo(
averageBitrate,
peakBitrate,
videoGroupId,
audioGroupId,
subtitlesGroupId,
closedCaptionsGroupId));
}
}
// TODO: Don't deduplicate variants by URL.
ArrayList<Variant> deduplicatedVariants = new ArrayList<>();
HashSet<Uri> urlsInDeduplicatedVariants = new HashSet<>();
for (int i = 0; i < variants.size(); i++) {
Variant variant = variants.get(i);
if (urlsInDeduplicatedVariants.add(variant.url)) {
Assertions.checkState(variant.format.metadata == null);
HlsTrackMetadataEntry hlsMetadataEntry =
new HlsTrackMetadataEntry(
/* groupId= */ null,
/* name= */ null,
Assertions.checkNotNull(urlToVariantInfos.get(variant.url)));
Metadata metadata = new Metadata(hlsMetadataEntry);
Format format = variant.format.buildUpon().setMetadata(metadata).build();
deduplicatedVariants.add(variant.copyWithFormat(format));
}
}
for (int i = 0; i < mediaTags.size(); i++) {
line = mediaTags.get(i);
String groupId = parseStringAttr(line, REGEX_GROUP_ID, variableDefinitions);
String name = parseStringAttr(line, REGEX_NAME, variableDefinitions);
Format.Builder formatBuilder =
new Format.Builder()
.setId(groupId + ":" + name)
.setLabel(name)
.setContainerMimeType(MimeTypes.APPLICATION_M3U8)
.setSelectionFlags(parseSelectionFlags(line))
.setRoleFlags(parseRoleFlags(line, variableDefinitions))
.setLanguage(parseOptionalStringAttr(line, REGEX_LANGUAGE, variableDefinitions));
@Nullable String referenceUri = parseOptionalStringAttr(line, REGEX_URI, variableDefinitions);
@Nullable Uri uri = referenceUri == null ? null : UriUtil.resolveToUri(baseUri, referenceUri);
Metadata metadata =
new Metadata(new HlsTrackMetadataEntry(groupId, name, Collections.emptyList()));
switch (parseStringAttr(line, REGEX_TYPE, variableDefinitions)) {
case TYPE_VIDEO:
@Nullable Variant variant = getVariantWithVideoGroup(variants, groupId);
if (variant != null) {
Format variantFormat = variant.format;
@Nullable
String codecs = Util.getCodecsOfType(variantFormat.codecs, C.TRACK_TYPE_VIDEO);
formatBuilder
.setCodecs(codecs)
.setSampleMimeType(MimeTypes.getMediaMimeType(codecs))
.setWidth(variantFormat.width)
.setHeight(variantFormat.height)
.setFrameRate(variantFormat.frameRate);
}
if (uri == null) {
// TODO: Remove this case and add a Rendition with a null uri to videos.
} else {
formatBuilder.setMetadata(metadata);
videos.add(new Rendition(uri, formatBuilder.build(), groupId, name));
}
break;
case TYPE_AUDIO:
@Nullable String sampleMimeType = null;
variant = getVariantWithAudioGroup(variants, groupId);
if (variant != null) {
@Nullable
String codecs = Util.getCodecsOfType(variant.format.codecs, C.TRACK_TYPE_AUDIO);
formatBuilder.setCodecs(codecs);
sampleMimeType = MimeTypes.getMediaMimeType(codecs);
}
@Nullable
String channelsString =
parseOptionalStringAttr(line, REGEX_CHANNELS, variableDefinitions);
if (channelsString != null) {
int channelCount = Integer.parseInt(Util.splitAtFirst(channelsString, "/")[0]);
formatBuilder.setChannelCount(channelCount);
if (MimeTypes.AUDIO_E_AC3.equals(sampleMimeType) && channelsString.endsWith("/JOC")) {
sampleMimeType = MimeTypes.AUDIO_E_AC3_JOC;
}
}
formatBuilder.setSampleMimeType(sampleMimeType);
if (uri == null) {
// TODO: Remove muxedAudioFormat and add a Rendition with a null uri to audios.
muxedAudioFormat = formatBuilder.build();
} else {
formatBuilder.setMetadata(metadata);
audios.add(new Rendition(uri, formatBuilder.build(), groupId, name));
}
break;
case TYPE_SUBTITLES:
sampleMimeType = null;
variant = getVariantWithSubtitleGroup(variants, groupId);
if (variant != null) {
@Nullable
String codecs = Util.getCodecsOfType(variant.format.codecs, C.TRACK_TYPE_TEXT);
formatBuilder.setCodecs(codecs);
sampleMimeType = MimeTypes.getMediaMimeType(codecs);
}
if (sampleMimeType == null) {
sampleMimeType = MimeTypes.TEXT_VTT;
}
formatBuilder.setSampleMimeType(sampleMimeType).setMetadata(metadata);
subtitles.add(new Rendition(uri, formatBuilder.build(), groupId, name));
break;
case TYPE_CLOSED_CAPTIONS:
String instreamId = parseStringAttr(line, REGEX_INSTREAM_ID, variableDefinitions);
int accessibilityChannel;
if (instreamId.startsWith("CC")) {
sampleMimeType = MimeTypes.APPLICATION_CEA608;
accessibilityChannel = Integer.parseInt(instreamId.substring(2));
} else /* starts with SERVICE */ {
sampleMimeType = MimeTypes.APPLICATION_CEA708;
accessibilityChannel = Integer.parseInt(instreamId.substring(7));
}
if (muxedCaptionFormats == null) {
muxedCaptionFormats = new ArrayList<>();
}
formatBuilder
.setSampleMimeType(sampleMimeType)
.setAccessibilityChannel(accessibilityChannel);
muxedCaptionFormats.add(formatBuilder.build());
// TODO: Remove muxedCaptionFormats and add a Rendition with a null uri to closedCaptions.
break;
default:
// Do nothing.
break;
}
}
if (noClosedCaptions) {
muxedCaptionFormats = Collections.emptyList();
}
return new HlsMasterPlaylist(
baseUri,
tags,
deduplicatedVariants,
videos,
audios,
subtitles,
closedCaptions,
muxedAudioFormat,
muxedCaptionFormats,
hasIndependentSegmentsTag,
variableDefinitions,
sessionKeyDrmInitData);
}
@Nullable
private static Variant getVariantWithAudioGroup(ArrayList<Variant> variants, String groupId) {
for (int i = 0; i < variants.size(); i++) {
Variant variant = variants.get(i);
if (groupId.equals(variant.audioGroupId)) {
return variant;
}
}
return null;
}
@Nullable
private static Variant getVariantWithVideoGroup(ArrayList<Variant> variants, String groupId) {
for (int i = 0; i < variants.size(); i++) {
Variant variant = variants.get(i);
if (groupId.equals(variant.videoGroupId)) {
return variant;
}
}
return null;
}
@Nullable
private static Variant getVariantWithSubtitleGroup(ArrayList<Variant> variants, String groupId) {
for (int i = 0; i < variants.size(); i++) {
Variant variant = variants.get(i);
if (groupId.equals(variant.subtitleGroupId)) {
return variant;
}
}
return null;
}
private static HlsMediaPlaylist parseMediaPlaylist(
HlsMasterPlaylist masterPlaylist, LineIterator iterator, String baseUri) throws IOException {
@HlsMediaPlaylist.PlaylistType int playlistType = HlsMediaPlaylist.PLAYLIST_TYPE_UNKNOWN;
long startOffsetUs = C.TIME_UNSET;
long mediaSequence = 0;
int version = 1; // Default version == 1.
long targetDurationUs = C.TIME_UNSET;
boolean hasIndependentSegmentsTag = masterPlaylist.hasIndependentSegments;
boolean hasEndTag = false;
@Nullable Segment initializationSegment = null;
HashMap<String, String> variableDefinitions = new HashMap<>();
HashMap<String, Segment> urlToInferredInitSegment = new HashMap<>();
List<Segment> segments = new ArrayList<>();
List<String> tags = new ArrayList<>();
long segmentDurationUs = 0;
String segmentTitle = "";
boolean hasDiscontinuitySequence = false;
int playlistDiscontinuitySequence = 0;
int relativeDiscontinuitySequence = 0;
long playlistStartTimeUs = 0;
long segmentStartTimeUs = 0;
long segmentByteRangeOffset = 0;
long segmentByteRangeLength = C.LENGTH_UNSET;
boolean isIFrameOnly = false;
long segmentMediaSequence = 0;
boolean hasGapTag = false;
DrmInitData playlistProtectionSchemes = null;
String fullSegmentEncryptionKeyUri = null;
String fullSegmentEncryptionIV = null;
TreeMap<String, SchemeData> currentSchemeDatas = new TreeMap<>();
String encryptionScheme = null;
DrmInitData cachedDrmInitData = null;
String line;
while (iterator.hasNext()) {
line = iterator.next();
if (line.startsWith(TAG_PREFIX)) {
// We expose all tags through the playlist.
tags.add(line);
}
if (line.startsWith(TAG_PLAYLIST_TYPE)) {
String playlistTypeString = parseStringAttr(line, REGEX_PLAYLIST_TYPE, variableDefinitions);
if ("VOD".equals(playlistTypeString)) {
playlistType = HlsMediaPlaylist.PLAYLIST_TYPE_VOD;
} else if ("EVENT".equals(playlistTypeString)) {
playlistType = HlsMediaPlaylist.PLAYLIST_TYPE_EVENT;
}
} else if (line.equals(TAG_IFRAME)) {
isIFrameOnly = true;
} else if (line.startsWith(TAG_START)) {
startOffsetUs = (long) (parseDoubleAttr(line, REGEX_TIME_OFFSET) * C.MICROS_PER_SECOND);
} else if (line.startsWith(TAG_INIT_SEGMENT)) {
String uri = parseStringAttr(line, REGEX_URI, variableDefinitions);
String byteRange = parseOptionalStringAttr(line, REGEX_ATTR_BYTERANGE, variableDefinitions);
if (byteRange != null) {
String[] splitByteRange = byteRange.split("@");
segmentByteRangeLength = Long.parseLong(splitByteRange[0]);
if (splitByteRange.length > 1) {
segmentByteRangeOffset = Long.parseLong(splitByteRange[1]);
}
}
if (fullSegmentEncryptionKeyUri != null && fullSegmentEncryptionIV == null) {
// See RFC 8216, Section 4.3.2.5.
throw new ParserException(
"The encryption IV attribute must be present when an initialization segment is "
+ "encrypted with METHOD=AES-128.");
}
initializationSegment =
new Segment(
uri,
segmentByteRangeOffset,
segmentByteRangeLength,
fullSegmentEncryptionKeyUri,
fullSegmentEncryptionIV);
segmentByteRangeOffset = 0;
segmentByteRangeLength = C.LENGTH_UNSET;
} else if (line.startsWith(TAG_TARGET_DURATION)) {
targetDurationUs = parseIntAttr(line, REGEX_TARGET_DURATION) * C.MICROS_PER_SECOND;
} else if (line.startsWith(TAG_MEDIA_SEQUENCE)) {
mediaSequence = parseLongAttr(line, REGEX_MEDIA_SEQUENCE);
segmentMediaSequence = mediaSequence;
} else if (line.startsWith(TAG_VERSION)) {
version = parseIntAttr(line, REGEX_VERSION);
} else if (line.startsWith(TAG_DEFINE)) {
String importName = parseOptionalStringAttr(line, REGEX_IMPORT, variableDefinitions);
if (importName != null) {
String value = masterPlaylist.variableDefinitions.get(importName);
if (value != null) {
variableDefinitions.put(importName, value);
} else {
// The master playlist does not declare the imported variable. Ignore.
}
} else {
variableDefinitions.put(
parseStringAttr(line, REGEX_NAME, variableDefinitions),
parseStringAttr(line, REGEX_VALUE, variableDefinitions));
}
} else if (line.startsWith(TAG_MEDIA_DURATION)) {
segmentDurationUs =
(long) (parseDoubleAttr(line, REGEX_MEDIA_DURATION) * C.MICROS_PER_SECOND);
segmentTitle = parseOptionalStringAttr(line, REGEX_MEDIA_TITLE, "", variableDefinitions);
} else if (line.startsWith(TAG_KEY)) {
String method = parseStringAttr(line, REGEX_METHOD, variableDefinitions);
String keyFormat =
parseOptionalStringAttr(line, REGEX_KEYFORMAT, KEYFORMAT_IDENTITY, variableDefinitions);
fullSegmentEncryptionKeyUri = null;
fullSegmentEncryptionIV = null;
if (METHOD_NONE.equals(method)) {
currentSchemeDatas.clear();
cachedDrmInitData = null;
} else /* !METHOD_NONE.equals(method) */ {
fullSegmentEncryptionIV = parseOptionalStringAttr(line, REGEX_IV, variableDefinitions);
if (KEYFORMAT_IDENTITY.equals(keyFormat)) {
if (METHOD_AES_128.equals(method)) {
// The segment is fully encrypted using an identity key.
fullSegmentEncryptionKeyUri = parseStringAttr(line, REGEX_URI, variableDefinitions);
} else {
// Do nothing. Samples are encrypted using an identity key, but this is not supported.
// Hopefully, a traditional DRM alternative is also provided.
}
} else {
if (encryptionScheme == null) {
encryptionScheme = parseEncryptionScheme(method);
}
SchemeData schemeData = parseDrmSchemeData(line, keyFormat, variableDefinitions);
if (schemeData != null) {
cachedDrmInitData = null;
currentSchemeDatas.put(keyFormat, schemeData);
}
}
}
} else if (line.startsWith(TAG_BYTERANGE)) {
String byteRange = parseStringAttr(line, REGEX_BYTERANGE, variableDefinitions);
String[] splitByteRange = byteRange.split("@");
segmentByteRangeLength = Long.parseLong(splitByteRange[0]);
if (splitByteRange.length > 1) {
segmentByteRangeOffset = Long.parseLong(splitByteRange[1]);
}
} else if (line.startsWith(TAG_DISCONTINUITY_SEQUENCE)) {
hasDiscontinuitySequence = true;
playlistDiscontinuitySequence = Integer.parseInt(line.substring(line.indexOf(':') + 1));
} else if (line.equals(TAG_DISCONTINUITY)) {
relativeDiscontinuitySequence++;
} else if (line.startsWith(TAG_PROGRAM_DATE_TIME)) {
if (playlistStartTimeUs == 0) {
long programDatetimeUs =
C.msToUs(Util.parseXsDateTime(line.substring(line.indexOf(':') + 1)));
playlistStartTimeUs = programDatetimeUs - segmentStartTimeUs;
}
} else if (line.equals(TAG_GAP)) {
hasGapTag = true;
} else if (line.equals(TAG_INDEPENDENT_SEGMENTS)) {
hasIndependentSegmentsTag = true;
} else if (line.equals(TAG_ENDLIST)) {
hasEndTag = true;
} else if (!line.startsWith("#")) {
String segmentEncryptionIV;
if (fullSegmentEncryptionKeyUri == null) {
segmentEncryptionIV = null;
} else if (fullSegmentEncryptionIV != null) {
segmentEncryptionIV = fullSegmentEncryptionIV;
} else {
segmentEncryptionIV = Long.toHexString(segmentMediaSequence);
}
segmentMediaSequence++;
String segmentUri = replaceVariableReferences(line, variableDefinitions);
@Nullable Segment inferredInitSegment = urlToInferredInitSegment.get(segmentUri);
if (segmentByteRangeLength == C.LENGTH_UNSET) {
// The segment is not byte range defined.
segmentByteRangeOffset = 0;
} else if (isIFrameOnly && initializationSegment == null && inferredInitSegment == null) {
// The segment is a resource byte range without an initialization segment.
// As per RFC 8216, Section 4.3.3.6, we assume the initialization section exists in the
// bytes preceding the first segment in this segment's URL.
// We assume the implicit initialization segment is unencrypted, since there's no way for
// the playlist to provide an initialization vector for it.
inferredInitSegment =
new Segment(
segmentUri,
/* byteRangeOffset= */ 0,
segmentByteRangeOffset,
/* fullSegmentEncryptionKeyUri= */ null,
/* encryptionIV= */ null);
urlToInferredInitSegment.put(segmentUri, inferredInitSegment);
}
if (cachedDrmInitData == null && !currentSchemeDatas.isEmpty()) {
SchemeData[] schemeDatas = currentSchemeDatas.values().toArray(new SchemeData[0]);
cachedDrmInitData = new DrmInitData(encryptionScheme, schemeDatas);
if (playlistProtectionSchemes == null) {
SchemeData[] playlistSchemeDatas = new SchemeData[schemeDatas.length];
for (int i = 0; i < schemeDatas.length; i++) {
playlistSchemeDatas[i] = schemeDatas[i].copyWithData(null);
}
playlistProtectionSchemes = new DrmInitData(encryptionScheme, playlistSchemeDatas);
}
}
segments.add(
new Segment(
segmentUri,
initializationSegment != null ? initializationSegment : inferredInitSegment,
segmentTitle,
segmentDurationUs,
relativeDiscontinuitySequence,
segmentStartTimeUs,
cachedDrmInitData,
fullSegmentEncryptionKeyUri,
segmentEncryptionIV,
segmentByteRangeOffset,
segmentByteRangeLength,
hasGapTag));
segmentStartTimeUs += segmentDurationUs;
segmentDurationUs = 0;
segmentTitle = "";
if (segmentByteRangeLength != C.LENGTH_UNSET) {
segmentByteRangeOffset += segmentByteRangeLength;
}
segmentByteRangeLength = C.LENGTH_UNSET;
hasGapTag = false;
}
}
return new HlsMediaPlaylist(
playlistType,
baseUri,
tags,
startOffsetUs,
playlistStartTimeUs,
hasDiscontinuitySequence,
playlistDiscontinuitySequence,
mediaSequence,
version,
targetDurationUs,
hasIndependentSegmentsTag,
hasEndTag,
/* hasProgramDateTime= */ playlistStartTimeUs != 0,
playlistProtectionSchemes,
segments);
}
@C.SelectionFlags
private static int parseSelectionFlags(String line) {
int flags = 0;
if (parseOptionalBooleanAttribute(line, REGEX_DEFAULT, false)) {
flags |= C.SELECTION_FLAG_DEFAULT;
}
if (parseOptionalBooleanAttribute(line, REGEX_FORCED, false)) {
flags |= C.SELECTION_FLAG_FORCED;
}
if (parseOptionalBooleanAttribute(line, REGEX_AUTOSELECT, false)) {
flags |= C.SELECTION_FLAG_AUTOSELECT;
}
return flags;
}
@C.RoleFlags
private static int parseRoleFlags(String line, Map<String, String> variableDefinitions) {
String concatenatedCharacteristics =
parseOptionalStringAttr(line, REGEX_CHARACTERISTICS, variableDefinitions);
if (TextUtils.isEmpty(concatenatedCharacteristics)) {
return 0;
}
String[] characteristics = Util.split(concatenatedCharacteristics, ",");
@C.RoleFlags int roleFlags = 0;
if (Util.contains(characteristics, "public.accessibility.describes-video")) {
roleFlags |= C.ROLE_FLAG_DESCRIBES_VIDEO;
}
if (Util.contains(characteristics, "public.accessibility.transcribes-spoken-dialog")) {
roleFlags |= C.ROLE_FLAG_TRANSCRIBES_DIALOG;
}
if (Util.contains(characteristics, "public.accessibility.describes-music-and-sound")) {
roleFlags |= C.ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND;
}
if (Util.contains(characteristics, "public.easy-to-read")) {
roleFlags |= C.ROLE_FLAG_EASY_TO_READ;
}
return roleFlags;
}
@Nullable
private static SchemeData parseDrmSchemeData(
String line, String keyFormat, Map<String, String> variableDefinitions)
throws ParserException {
String keyFormatVersions =
parseOptionalStringAttr(line, REGEX_KEYFORMATVERSIONS, "1", variableDefinitions);
if (KEYFORMAT_WIDEVINE_PSSH_BINARY.equals(keyFormat)) {
String uriString = parseStringAttr(line, REGEX_URI, variableDefinitions);
return new SchemeData(
C.WIDEVINE_UUID,
MimeTypes.VIDEO_MP4,
Base64.decode(uriString.substring(uriString.indexOf(',')), Base64.DEFAULT));
} else if (KEYFORMAT_WIDEVINE_PSSH_JSON.equals(keyFormat)) {
return new SchemeData(C.WIDEVINE_UUID, "hls", Util.getUtf8Bytes(line));
} else if (KEYFORMAT_PLAYREADY.equals(keyFormat) && "1".equals(keyFormatVersions)) {
String uriString = parseStringAttr(line, REGEX_URI, variableDefinitions);
byte[] data = Base64.decode(uriString.substring(uriString.indexOf(',')), Base64.DEFAULT);
byte[] psshData = PsshAtomUtil.buildPsshAtom(C.PLAYREADY_UUID, data);
return new SchemeData(C.PLAYREADY_UUID, MimeTypes.VIDEO_MP4, psshData);
}
return null;
}
private static String parseEncryptionScheme(String method) {
return METHOD_SAMPLE_AES_CENC.equals(method) || METHOD_SAMPLE_AES_CTR.equals(method)
? C.CENC_TYPE_cenc
: C.CENC_TYPE_cbcs;
}
private static int parseIntAttr(String line, Pattern pattern) throws ParserException {
return Integer.parseInt(parseStringAttr(line, pattern, Collections.emptyMap()));
}
private static int parseOptionalIntAttr(String line, Pattern pattern, int defaultValue) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return Integer.parseInt(Assertions.checkNotNull(matcher.group(1)));
}
return defaultValue;
}
private static long parseLongAttr(String line, Pattern pattern) throws ParserException {
return Long.parseLong(parseStringAttr(line, pattern, Collections.emptyMap()));
}
private static double parseDoubleAttr(String line, Pattern pattern) throws ParserException {
return Double.parseDouble(parseStringAttr(line, pattern, Collections.emptyMap()));
}
private static String parseStringAttr(
String line, Pattern pattern, Map<String, String> variableDefinitions)
throws ParserException {
String value = parseOptionalStringAttr(line, pattern, variableDefinitions);
if (value != null) {
return value;
} else {
throw new ParserException("Couldn't match " + pattern.pattern() + " in " + line);
}
}
private static @Nullable String parseOptionalStringAttr(
String line, Pattern pattern, Map<String, String> variableDefinitions) {
return parseOptionalStringAttr(line, pattern, null, variableDefinitions);
}
private static @PolyNull String parseOptionalStringAttr(
String line,
Pattern pattern,
@PolyNull String defaultValue,
Map<String, String> variableDefinitions) {
Matcher matcher = pattern.matcher(line);
@PolyNull
String value = matcher.find() ? Assertions.checkNotNull(matcher.group(1)) : defaultValue;
return variableDefinitions.isEmpty() || value == null
? value
: replaceVariableReferences(value, variableDefinitions);
}
private static String replaceVariableReferences(
String string, Map<String, String> variableDefinitions) {
Matcher matcher = REGEX_VARIABLE_REFERENCE.matcher(string);
// TODO: Replace StringBuffer with StringBuilder once Java 9 is available.
StringBuffer stringWithReplacements = new StringBuffer();
while (matcher.find()) {
String groupName = matcher.group(1);
if (variableDefinitions.containsKey(groupName)) {
matcher.appendReplacement(
stringWithReplacements, Matcher.quoteReplacement(variableDefinitions.get(groupName)));
} else {
// The variable is not defined. The value is ignored.
}
}
matcher.appendTail(stringWithReplacements);
return stringWithReplacements.toString();
}
private static boolean parseOptionalBooleanAttribute(
String line, Pattern pattern, boolean defaultValue) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return BOOLEAN_TRUE.equals(matcher.group(1));
}
return defaultValue;
}
private static Pattern compileBooleanAttrPattern(String attribute) {
return Pattern.compile(attribute + "=(" + BOOLEAN_FALSE + "|" + BOOLEAN_TRUE + ")");
}
private static class LineIterator {
private final BufferedReader reader;
private final Queue<String> extraLines;
@Nullable private String next;
public LineIterator(Queue<String> extraLines, BufferedReader reader) {
this.extraLines = extraLines;
this.reader = reader;
}
@EnsuresNonNullIf(expression = "next", result = true)
public boolean hasNext() throws IOException {
if (next != null) {
return true;
}
if (!extraLines.isEmpty()) {
next = Assertions.checkNotNull(extraLines.poll());
return true;
}
while ((next = reader.readLine()) != null) {
next = next.trim();
if (!next.isEmpty()) {
return true;
}
}
return false;
}
/** Return the next line, or throw {@link NoSuchElementException} if none. */
public String next() throws IOException {
if (hasNext()) {
String result = next;
next = null;
return result;
} else {
throw new NoSuchElementException();
}
}
}
}
| Fix chunkless preparation for playlists with dangling EXT-X-MEDIA tags
We are not able to associate a codecs attribute to an EXT-X-MEDIA tag if
there is no variant with a matching AUDIO GROUP-ID. Lack of codecs string
prevents chunkless preparation from determining the track type.
Issue: #7678
PiperOrigin-RevId: 324822415
| library/hls/src/main/java/com/google/android/exoplayer2/source/hls/playlist/HlsPlaylistParser.java | Fix chunkless preparation for playlists with dangling EXT-X-MEDIA tags | <ide><path>ibrary/hls/src/main/java/com/google/android/exoplayer2/source/hls/playlist/HlsPlaylistParser.java
<ide> }
<ide> }
<ide> formatBuilder.setSampleMimeType(sampleMimeType);
<del> if (uri == null) {
<add> if (uri != null) {
<add> formatBuilder.setMetadata(metadata);
<add> audios.add(new Rendition(uri, formatBuilder.build(), groupId, name));
<add> } else if (variant != null) {
<ide> // TODO: Remove muxedAudioFormat and add a Rendition with a null uri to audios.
<ide> muxedAudioFormat = formatBuilder.build();
<del> } else {
<del> formatBuilder.setMetadata(metadata);
<del> audios.add(new Rendition(uri, formatBuilder.build(), groupId, name));
<ide> }
<ide> break;
<ide> case TYPE_SUBTITLES: |
|
Java | mit | 3d12a63ef4b4708a09352042876393c3e1ea3487 | 0 | jpush/aurora-imui,jpush/aurora-imui,jpush/aurora-imui,jpush/aurora-imui,jpush/aurora-imui | package cn.jiguang.imui.messages;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import cn.jiguang.imui.R;
import cn.jiguang.imui.commons.models.FileItem;
import cn.jiguang.imui.utils.ImgBrowserViewPager;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
public class PhotoAdapter extends PagerAdapter {
private ImgBrowserViewPager mImgViewPager;
private List<FileItem> mPhotos = new ArrayList<>();
private SparseBooleanArray mSelectedItems = new SparseBooleanArray();
private List<String> mSendFiles;
private Bitmap mBitmap;
private OnFileSelectedListener mListener;
public PhotoAdapter(ImgBrowserViewPager viewPager, List<FileItem> list) {
this.mImgViewPager = viewPager;
this.mPhotos = list;
}
@Override
public int getCount() {
return mPhotos.size();
}
@Override
public float getPageWidth(int position) {
return (float) 0.8;
}
/**
* 点击某张图片预览时,系统自动调用此方法加载这张图片左右视图(如果有的话)
*/
@Override
public View instantiateItem(final ViewGroup container, final int position) {
View view = LayoutInflater.from(container.getContext()).inflate(R.layout.item_photo_select, container, false);
final ImageView photoView = (ImageView) view.findViewById(R.id.item_photo_iv);
final ImageView shadow = (ImageView) view.findViewById(R.id.item_shadow_iv);
final ImageView checkedIcon = (ImageView) view.findViewById(R.id.checked_iv);
photoView.setTag(position);
photoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
String path = mPhotos.get(position).getFilePath();
if (path != null) {
File file = new File(path);
if (file.exists()) {
mBitmap = decodeFile(file);
if (mBitmap != null) {
photoView.setImageBitmap(mBitmap);
} else {
photoView.setImageResource(R.drawable.jmui_picture_not_found);
}
}
} else {
photoView.setImageResource(R.drawable.jmui_picture_not_found);
}
photoView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (checkedIcon.getVisibility() == GONE && !mSelectedItems.get(position)) {
mSelectedItems.put(position, true);
checkedIcon.setVisibility(VISIBLE);
addSelectedAnimation(photoView, shadow);
shadow.setVisibility(VISIBLE);
mSendFiles.add(mPhotos.get(position).getFilePath());
if (mListener != null) {
mListener.onFileSelected();
}
} else {
addDeselectedAnimation(photoView, shadow);
checkedIcon.setVisibility(GONE);
shadow.setVisibility(GONE);
mSelectedItems.delete(position);
mSendFiles.remove(mPhotos.get(position).getFilePath());
if (mListener != null) {
mListener.onFileDeselected();
}
}
}
});
container.addView(view, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.MATCH_PARENT);
return view;
}
@Override
public int getItemPosition(Object object) {
View view = (View) object;
int currentPage = mImgViewPager.getCurrentItem();
if (currentPage == (Integer) view.getTag()) {
return POSITION_NONE;
} else {
return POSITION_UNCHANGED;
}
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
private Bitmap decodeFile(File f) {
Bitmap b = null;
try {
//Decode image size
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, options);
fis.close();
int width = options.outWidth;
int height = options.outHeight;
int ratio = 0;
//如果宽度大于高度,交换宽度和高度
if (width > height) {
int temp = width;
width = height;
height = temp;
}
//计算取样比例
int sampleRatio = Math.max(width / 900, height / 1600);
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = sampleRatio;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
private void addDeselectedAnimation(View... views) {
List<Animator> valueAnimators = new ArrayList<>();
for (View v : views) {
ObjectAnimator scaleX = ObjectAnimator.ofFloat(v, "scaleX", 1.0f);
ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 1.0f);
valueAnimators.add(scaleX);
valueAnimators.add(scaleY);
}
AnimatorSet set = new AnimatorSet();
set.playTogether(valueAnimators);
set.setDuration(150);
set.start();
}
private void addSelectedAnimation(View... views) {
List<Animator> valueAnimators = new ArrayList<>();
for (View v : views) {
ObjectAnimator scaleX = ObjectAnimator.ofFloat(v, "scaleX", 0.8f);
ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 0.8f);
valueAnimators.add(scaleX);
valueAnimators.add(scaleY);
}
AnimatorSet set = new AnimatorSet();
set.playTogether(valueAnimators);
set.setDuration(150);
set.start();
}
public List<String> getSelectedFiles() {
return mSendFiles;
}
public void setOnPhotoSelectedListener(OnFileSelectedListener listener) {
mListener = listener;
}
public void setSelectedFiles(List<String> list) {
mSendFiles = list;
}
public interface OnFileSelectedListener {
void onFileSelected();
void onFileDeselected();
}
}
| android/src/main/java/cn/jiguang/imui/messages/PhotoAdapter.java | package cn.jiguang.imui.messages;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import cn.jiguang.imui.R;
import cn.jiguang.imui.commons.models.FileItem;
import cn.jiguang.imui.utils.ImgBrowserViewPager;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
public class PhotoAdapter extends PagerAdapter {
private ImgBrowserViewPager mImgViewPager;
private List<FileItem> mPhotos = new ArrayList<>();
private SparseBooleanArray mSelectedItems = new SparseBooleanArray();
private List<String> mSendFiles;
private Bitmap mBitmap;
private OnFileSelectedListener mListener;
public PhotoAdapter(ImgBrowserViewPager viewPager, List<FileItem> list) {
this.mImgViewPager = viewPager;
this.mPhotos = list;
}
@Override
public int getCount() {
return mPhotos.size();
}
@Override
public float getPageWidth(int position) {
return (float) 0.8;
}
/**
* 点击某张图片预览时,系统自动调用此方法加载这张图片左右视图(如果有的话)
*/
@Override
public View instantiateItem(final ViewGroup container, final int position) {
View view = LayoutInflater.from(container.getContext()).inflate(R.layout.item_photo_select, container, false);
final ImageView photoView = (ImageView) view.findViewById(R.id.item_photo_iv);
final ImageView shadow = (ImageView) view.findViewById(R.id.item_shadow_iv);
final ImageView checkedIcon = (ImageView) view.findViewById(R.id.checked_iv);
photoView.setTag(position);
photoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
String path = mPhotos.get(position).getFilePath();
if (path != null) {
File file = new File(path);
if (file.exists()) {
mBitmap = decodeFile(file);
if (mBitmap != null) {
photoView.setImageBitmap(mBitmap);
} else {
photoView.setImageResource(R.drawable.jmui_picture_not_found);
}
}
} else {
photoView.setImageResource(R.drawable.jmui_picture_not_found);
}
photoView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (checkedIcon.getVisibility() == GONE && !mSelectedItems.get(position)) {
mSelectedItems.put(position, true);
checkedIcon.setVisibility(VISIBLE);
addSelectedAnimation(photoView);
addSelectedAnimation(shadow);
shadow.setVisibility(VISIBLE);
mSendFiles.add(mPhotos.get(position).getFilePath());
if (mListener != null) {
mListener.onFileSelected();
}
} else {
addDeselectedAnimation(photoView);
checkedIcon.setVisibility(GONE);
shadow.setVisibility(GONE);
mSelectedItems.delete(position);
mSendFiles.remove(mPhotos.get(position).getFilePath());
if (mListener != null) {
mListener.onFileDeselected();
}
}
}
});
container.addView(view, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.MATCH_PARENT);
return view;
}
@Override
public int getItemPosition(Object object) {
View view = (View) object;
int currentPage = mImgViewPager.getCurrentItem();
if (currentPage == (Integer) view.getTag()) {
return POSITION_NONE;
} else {
return POSITION_UNCHANGED;
}
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
private Bitmap decodeFile(File f) {
Bitmap b = null;
try {
//Decode image size
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, options);
fis.close();
int width = options.outWidth;
int height = options.outHeight;
int ratio = 0;
//如果宽度大于高度,交换宽度和高度
if (width > height) {
int temp = width;
width = height;
height = temp;
}
//计算取样比例
int sampleRatio = Math.max(width / 900, height / 1600);
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = sampleRatio;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
private void addDeselectedAnimation(ImageView view) {
float[] vaules = new float[]{1.0f, 1.1f, 1.2f, 1.3f, 1.2f, 1.1f, 1.0f, 0.9f, 0.8f, 0.7f, 0.75f,
0.80f, 0.85f, 0.9f, 0.95f, 1.0f};
AnimatorSet set = new AnimatorSet();
set.playTogether(ObjectAnimator.ofFloat(view, "scaleX", vaules),
ObjectAnimator.ofFloat(view, "scaleY", vaules));
set.setDuration(150);
set.start();
}
private void addSelectedAnimation(View view) {
float[] vaules = new float[]{0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 0.8f, 0.7f, 0.6f, 0.65f, 0.7f,
0.75f, 0.80f, 0.85f, 0.9f};
AnimatorSet set = new AnimatorSet();
set.playTogether(ObjectAnimator.ofFloat(view, "scaleX", vaules),
ObjectAnimator.ofFloat(view, "scaleY", vaules));
set.setDuration(150);
set.start();
}
public List<String> getSelectedFiles() {
return mSendFiles;
}
public void setOnPhotoSelectedListener(OnFileSelectedListener listener) {
mListener = listener;
}
public void setSelectedFiles(List<String> list) {
mSendFiles = list;
}
public interface OnFileSelectedListener {
void onFileSelected();
void onFileDeselected();
}
}
| Modify the effect of selected images.
| android/src/main/java/cn/jiguang/imui/messages/PhotoAdapter.java | Modify the effect of selected images. | <ide><path>ndroid/src/main/java/cn/jiguang/imui/messages/PhotoAdapter.java
<ide> package cn.jiguang.imui.messages;
<ide>
<add>import android.animation.Animator;
<ide> import android.animation.AnimatorSet;
<ide> import android.animation.ObjectAnimator;
<ide> import android.graphics.Bitmap;
<ide> if (checkedIcon.getVisibility() == GONE && !mSelectedItems.get(position)) {
<ide> mSelectedItems.put(position, true);
<ide> checkedIcon.setVisibility(VISIBLE);
<del> addSelectedAnimation(photoView);
<del> addSelectedAnimation(shadow);
<add> addSelectedAnimation(photoView, shadow);
<ide> shadow.setVisibility(VISIBLE);
<ide> mSendFiles.add(mPhotos.get(position).getFilePath());
<ide> if (mListener != null) {
<ide> mListener.onFileSelected();
<ide> }
<ide> } else {
<del> addDeselectedAnimation(photoView);
<add> addDeselectedAnimation(photoView, shadow);
<ide> checkedIcon.setVisibility(GONE);
<ide> shadow.setVisibility(GONE);
<ide> mSelectedItems.delete(position);
<ide> return b;
<ide> }
<ide>
<del> private void addDeselectedAnimation(ImageView view) {
<del> float[] vaules = new float[]{1.0f, 1.1f, 1.2f, 1.3f, 1.2f, 1.1f, 1.0f, 0.9f, 0.8f, 0.7f, 0.75f,
<del> 0.80f, 0.85f, 0.9f, 0.95f, 1.0f};
<add> private void addDeselectedAnimation(View... views) {
<add> List<Animator> valueAnimators = new ArrayList<>();
<add> for (View v : views) {
<add> ObjectAnimator scaleX = ObjectAnimator.ofFloat(v, "scaleX", 1.0f);
<add> ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 1.0f);
<add>
<add> valueAnimators.add(scaleX);
<add> valueAnimators.add(scaleY);
<add> }
<add>
<ide> AnimatorSet set = new AnimatorSet();
<del> set.playTogether(ObjectAnimator.ofFloat(view, "scaleX", vaules),
<del> ObjectAnimator.ofFloat(view, "scaleY", vaules));
<add> set.playTogether(valueAnimators);
<ide> set.setDuration(150);
<ide> set.start();
<ide> }
<ide>
<del> private void addSelectedAnimation(View view) {
<del> float[] vaules = new float[]{0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 0.8f, 0.7f, 0.6f, 0.65f, 0.7f,
<del> 0.75f, 0.80f, 0.85f, 0.9f};
<add> private void addSelectedAnimation(View... views) {
<add> List<Animator> valueAnimators = new ArrayList<>();
<add> for (View v : views) {
<add> ObjectAnimator scaleX = ObjectAnimator.ofFloat(v, "scaleX", 0.8f);
<add> ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 0.8f);
<add>
<add> valueAnimators.add(scaleX);
<add> valueAnimators.add(scaleY);
<add> }
<add>
<ide> AnimatorSet set = new AnimatorSet();
<del> set.playTogether(ObjectAnimator.ofFloat(view, "scaleX", vaules),
<del> ObjectAnimator.ofFloat(view, "scaleY", vaules));
<add> set.playTogether(valueAnimators);
<ide> set.setDuration(150);
<ide> set.start();
<ide> } |
|
Java | epl-1.0 | 309d813f6e675395efe6a6006c4f6795d9fba17f | 0 | Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt | /*******************************************************************************
* Copyright (c) 2004, 2008 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.dialogs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.designer.data.ui.util.SelectValueFetcher;
import org.eclipse.birt.report.designer.internal.ui.expressions.IExpressionConverter;
import org.eclipse.birt.report.designer.internal.ui.swt.custom.MultiValueCombo;
import org.eclipse.birt.report.designer.internal.ui.swt.custom.ValueCombo;
import org.eclipse.birt.report.designer.internal.ui.util.DataUtil;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.ExpressionButtonUtil;
import org.eclipse.birt.report.designer.internal.ui.util.ExpressionUtility;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.util.ExceptionUtil;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.designer.util.AlphabeticallyComparator;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.Expression;
import org.eclipse.birt.report.model.api.FilterConditionHandle;
import org.eclipse.birt.report.model.api.ListingHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.FilterCondition;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.metadata.IChoiceSet;
import org.eclipse.birt.report.model.api.olap.TabularCubeHandle;
import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
/**
* Dialog for adding or editing map rule.
*/
public class FilterConditionBuilder extends BaseTitleAreaDialog
{
protected static Logger logger = Logger.getLogger( FilterConditionBuilder.class.getName( ) );
public static final String DLG_TITLE_NEW = Messages.getString( "FilterConditionBuilder.DialogTitle.New" ); //$NON-NLS-1$
public static final String DLG_TITLE_EDIT = Messages.getString( "FilterConditionBuilder.DialogTitle.Edit" ); //$NON-NLS-1$
public static final String DLG_MESSAGE_NEW = Messages.getString( "FilterConditionBuilder.DialogMessage.New" ); //$NON-NLS-1$
public static final String DLG_MESSAGE_EDIT = Messages.getString( "FilterConditionBuilder.DialogMessage.Edit" ); //$NON-NLS-1$
protected transient String[] popupItems = null;
private static String[] actions = new String[]{
Messages.getString( "ExpressionValueCellEditor.selectValueAction" ), //$NON-NLS-1$
Messages.getString( "ExpressionValueCellEditor.buildExpressionAction" ), //$NON-NLS-1$
};
protected final String NULL_STRING = null;
protected Composite dummy1, dummy2;
protected Label label1, label2;
protected List valueList = new ArrayList( );
protected List selValueList = new ArrayList( );
/**
* Usable operators for building map rule conditions.
*/
protected static final String[][] OPERATOR;
private transient String bindingName;
private ParamBindingHandle[] bindingParams = null;
private transient boolean refreshItems = true;
protected transient ReportElementHandle currentItem = null;
protected static final String[] EMPTY_ARRAY = new String[]{};
protected List columnList;
protected int valueVisible;
protected Table table;
protected TableViewer tableViewer;
/**
* Constant, represents empty String array.
*/
protected static final String[] EMPTY = new String[0];
public void setReportElement( ReportElementHandle reportItem )
{
currentItem = reportItem;
}
/**
* @param bindingName
* The selectValueExpression to set.
*/
public void setBindingName( String bindingName )
{
this.bindingName = bindingName;
}
/**
*
*/
public void setBindingParams( ParamBindingHandle[] params )
{
this.bindingParams = params;
}
/**
* @param title
*/
public FilterConditionBuilder( String title, String message )
{
this( UIUtil.getDefaultShell( ), title, message );
}
protected String title, message;
protected IChoiceSet choiceSet;
/**
* @param parentShell
* @param title
*/
public FilterConditionBuilder( Shell parentShell, String title,
String message )
{
super( parentShell );
this.title = title;
this.message = message;
}
static
{
IChoiceSet chset = ChoiceSetFactory.getStructChoiceSet( FilterCondition.FILTER_COND_STRUCT,
FilterCondition.OPERATOR_MEMBER );
IChoice[] chs = chset.getChoices( new AlphabeticallyComparator( ) );
OPERATOR = new String[chs.length][2];
for ( int i = 0; i < chs.length; i++ )
{
OPERATOR[i][0] = chs[i].getDisplayName( );
OPERATOR[i][1] = chs[i].getName( );
}
}
/**
* Returns the operator value by its display name.
*
* @param name
*/
public static String getValueForOperator( String name )
{
for ( int i = 0; i < OPERATOR.length; i++ )
{
if ( OPERATOR[i][0].equals( name ) )
{
return OPERATOR[i][1];
}
}
return null;
}
/**
* Returns how many value fields this operator needs.
*
* @param operatorValue
*/
public static int determineValueVisible( String operatorValue )
{
if ( DesignChoiceConstants.FILTER_OPERATOR_ANY.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_FALSE.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_TRUE.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_NULL.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_NOT_NULL.equals( operatorValue ) )
{
return 0;
}
else if ( DesignChoiceConstants.FILTER_OPERATOR_LT.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_LE.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_EQ.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_NE.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_GE.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_GT.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_LIKE.equals( operatorValue ) )
{
return 1;
}
else if ( DesignChoiceConstants.FILTER_OPERATOR_BETWEEN.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_NOT_BETWEEN.equals( operatorValue ) )
{
return 2;
}
else if ( DesignChoiceConstants.FILTER_OPERATOR_IN.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_NOT_IN.equals( operatorValue ) )
{
return 3;
}
return 1;
}
/**
* Returns the operator display name by its value.
*
* @param value
*/
public static String getNameForOperator( String value )
{
for ( int i = 0; i < OPERATOR.length; i++ )
{
if ( OPERATOR[i][1].equals( value ) )
{
return OPERATOR[i][0];
}
}
return ""; //$NON-NLS-1$
}
/**
* Returns the index for given operator value in the operator list.
*
* @param value
*/
protected static int getIndexForOperatorValue( String value )
{
for ( int i = 0; i < OPERATOR.length; i++ )
{
if ( OPERATOR[i][1].equals( value ) )
{
return i;
}
}
return 0;
}
protected FilterConditionHandle filterCondition;
protected Combo expression, operator;
protected Button addBtn, editBtn, delBtn, delAllBtn;
protected ValueCombo expressionValue1, expressionValue2;
protected MultiValueCombo addExpressionValue;
protected Composite valueListComposite;
protected Label andLable;
protected DesignElementHandle designHandle;
protected DataSetHandle dataSetHandle;
protected String[] getDataSetColumns( )
{
if ( columnList.isEmpty( ) )
{
return EMPTY;
}
String[] values = new String[columnList.size( )];
for ( int i = 0; i < columnList.size( ); i++ )
{
values[i] = getColumnName( columnList.get( i ) );
}
return values;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.dialogs.Dialog#createContents(org.eclipse.swt.widgets
* .Composite)
*/
protected Control createDialogArea( Composite parent )
{
UIUtil.bindHelp( parent,
IHelpContextIds.INSERT_EDIT_FILTER_CONDITION_DIALOG_ID );
Composite area = (Composite) super.createDialogArea( parent );
Composite contents = new Composite( area, SWT.NONE );
contents.setLayoutData( new GridData( GridData.FILL_BOTH ) );
contents.setLayout( new GridLayout( ) );
this.setTitle( title );
this.setMessage( message );
getShell( ).setText( title );
applyDialogFont( contents );
initializeDialogUnits( area );
createFilterConditionContent( contents );
return area;
}
protected void createFilterConditionContent( Composite innerParent )
{
Composite anotherParent = new Composite( innerParent, SWT.NONE );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
anotherParent.setLayoutData( gd );
GridLayout glayout = new GridLayout( 4, false );
anotherParent.setLayout( glayout );
Label lb = new Label( anotherParent, SWT.NONE );
lb.setText( Messages.getString( "FilterConditionBuilder.text.Condition" ) ); //$NON-NLS-1$
Label lb2 = new Label( anotherParent, SWT.NONE );
lb2.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
new Label( anotherParent, SWT.NONE );
Composite condition = new Composite( innerParent, SWT.NONE );
gd = new GridData( GridData.FILL_BOTH );
gd.heightHint = 220;
condition.setLayoutData( gd );
glayout = new GridLayout( 4, false );
condition.setLayout( glayout );
expression = new Combo( condition, SWT.NONE );
GridData gdata = new GridData( );
gdata.widthHint = 100;
expression.setLayoutData( gdata );
expression.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
IExpressionConverter converter = ExpressionButtonUtil.getCurrentExpressionConverter( expression );
if ( converter != null )
{
if ( expression.getSelectionIndex( ) >= 0 )
{
String newValue = expression.getItem( expression.getSelectionIndex( ) );
String value = ExpressionUtility.getColumnExpression( newValue,
converter );
if ( value != null )
newValue = value;
expression.setText( newValue );
}
}
updateButtons( );
}
} );
expression.setItems( getDataSetColumns( ) );
if ( expression.getItemCount( ) == 0 )
{
expression.add( DEUtil.resolveNull( null ) );
}
expression.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
updateButtons( );
}
} );
Listener listener = new Listener( ) {
public void handleEvent( Event event )
{
updateButtons( );
}
};
ExpressionButtonUtil.createExpressionButton( condition,
expression,
getExpressionProvider( ),
dataSetHandle != null ? dataSetHandle : designHandle,
listener );
operator = new Combo( condition, SWT.READ_ONLY );
for ( int i = 0; i < OPERATOR.length; i++ )
{
operator.add( OPERATOR[i][0] );
}
operator.addSelectionListener( operatorSelection );
create2ValueComposite( condition );
if ( filterCondition != null )
{
syncViewProperties( );
}
lb = new Label( innerParent, SWT.SEPARATOR | SWT.HORIZONTAL );
lb.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
private IExpressionProvider getExpressionProvider( )
{
IExpressionProvider provider = null;
if ( expressionProvider == null )
{
if ( designHandle instanceof TabularCubeHandle
|| designHandle instanceof TabularHierarchyHandle )
{
provider = new BindingExpressionProvider( designHandle, null );
}
else
{
provider = new ExpressionProvider( designHandle );
}
}
else
{
provider = expressionProvider;
}
return provider;
}
// protected Listener expValueVerifyListener = new Listener( ) {
//
// public void handleEvent( Event event )
// {
// // TODO Auto-generated method stub
// Combo thisCombo = (Combo) event.widget;
// String text = event.text;
// if ( text != null && thisCombo.indexOf( text ) >= 0 )
// {
// event.doit = false;
// }
// else
// {
// event.doit = true;
// }
// }
// };
protected String getColumnName( Object obj )
{
if ( obj instanceof ComputedColumnHandle )
return ( (ComputedColumnHandle) obj ).getName( );
else if ( obj instanceof ResultSetColumnHandle )
return ( (ResultSetColumnHandle) obj ).getColumnName( );
else
return ""; //$NON-NLS-1$
}
// private Listener expValueSelectionListener = new Listener( ) {
//
// public void handleEvent( Event event )
// {
// // TODO Auto-generated method stub
// Combo thisCombo = (Combo) event.widget;
// int selectionIndex = thisCombo.getSelectionIndex( );
// if ( selectionIndex < 0 )
// {
// return;
// }
// String value = popupItems[selectionIndex];
//
// boolean isAddClick = false;
// if ( tableViewer != null
// && ( addBtn != null && ( !addBtn.isDisposed( ) ) ) )
// {
// isAddClick = true;
// }
//
// bindingName = null;
// for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); )
// {
// String columnName = getColumnName( iter.next( ) );
// if ( DEUtil.getColumnExpression( columnName )
// .equals( expression.getText( ) ) )
// {
// bindingName = columnName;
// break;
// }
// }
//
// boolean returnValue = false;
// if ( value != null )
// {
// String newValues[] = new String[1];
// if ( value.equals( ( actions[0] ) ) )
// {
// if ( bindingName != null )
// {
// try
// {
// List selectValueList = getSelectValueList( );
// SelectValueDialog dialog = new SelectValueDialog(
// PlatformUI.getWorkbench( )
// .getDisplay( )
// .getActiveShell( ),
// Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
// if ( isAddClick )
// {
// dialog.setMultipleSelection( true );
// }
// dialog.setSelectedValueList( selectValueList );
// if ( bindingParams != null )
// {
// dialog.setBindingParams( bindingParams );
// }
// if ( dialog.open( ) == IDialogConstants.OK_ID )
// {
// returnValue = true;
// newValues = dialog.getSelectedExprValues( );
// }
// }
// catch ( Exception ex )
// {
// MessageDialog.openError( null,
// Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
// Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
// + "\n" //$NON-NLS-1$
// + ex.getMessage( ) );
// }
// }
// else if ( designHandle instanceof TabularCubeHandle
// || designHandle instanceof TabularHierarchyHandle )
// {
// DataSetHandle dataSet;
// if ( designHandle instanceof TabularCubeHandle )
// dataSet = ( (TabularCubeHandle) designHandle ).getDataSet( );
// else
// {
// dataSet = ( (TabularHierarchyHandle) designHandle ).getDataSet( );
// if ( dataSet == null
// && ( (TabularHierarchyHandle) designHandle ).getLevelCount( ) > 0 )
// {
// dataSet = ( (TabularCubeHandle) ( (TabularHierarchyHandle) designHandle
// ).getContainer( )
// .getContainer( ) ).getDataSet( );
// }
// }
// String expressionString = expression.getText( );
// try
// {
// List selectValueList = SelectValueFetcher.getSelectValueList(
// expressionString,
// dataSet );
// SelectValueDialog dialog = new SelectValueDialog(
// PlatformUI.getWorkbench( )
// .getDisplay( )
// .getActiveShell( ),
// Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
// dialog.setSelectedValueList( selectValueList );
// if ( isAddClick )
// {
// dialog.setMultipleSelection( true );
// }
// if ( dialog.open( ) == IDialogConstants.OK_ID )
// {
// returnValue = true;
// newValues = dialog.getSelectedExprValues( );
//
// }
//
// }
// catch ( BirtException e1 )
// {
// // TODO Auto-generated catch block
// MessageDialog.openError( null,
// Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
// Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
// + "\n" //$NON-NLS-1$
// + e1.getMessage( ) );
// }
// }
// else
// {
// MessageDialog.openInformation( null,
// Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
// Messages.getString( "SelectValueDialog.messages.info.selectVauleUnavailable" ) ); //$NON-NLS-1$
// }
// }
// else if ( value.equals( actions[1] ) )
// {
// ExpressionBuilder dialog = new ExpressionBuilder(
// PlatformUI.getWorkbench( )
// .getDisplay( )
// .getActiveShell( ),
// thisCombo.getText( ) );
//
// if ( designHandle != null )
// {
// if ( expressionProvider == null )
// {
// if ( designHandle instanceof TabularCubeHandle
// || designHandle instanceof TabularHierarchyHandle )
// {
// dialog.setExpressionProvier( new BindingExpressionProvider( designHandle,
// null ) );
// }
// else
// {
// dialog.setExpressionProvier( new ExpressionProvider( designHandle ) );
// }
// }
// else
// {
// dialog.setExpressionProvier( expressionProvider );
// }
// }
//
// if ( dialog.open( ) == IDialogConstants.OK_ID )
// {
// returnValue = true;
// newValues[0] = dialog.getResult( );
// }
// }
// else if ( selectionIndex > 3 )
// {
// newValues[0] = "params[\"" + value + "\"]"; //$NON-NLS-1$ //$NON-NLS-2$
// }
//
// if ( returnValue )
// {
// if ( addExpressionValue == thisCombo )
// {
// thisCombo.setText( "" ); //$NON-NLS-1$
// addBtn.setEnabled( false );
// }
// else if ( newValues.length == 1 )
// {
// thisCombo.setText( DEUtil.resolveNull( newValues[0] ) );
// }
//
// if ( isAddClick )
// {
//
// boolean change = false;
// for ( int i = 0; i < newValues.length; i++ )
// {
// if ( valueList.indexOf( DEUtil.resolveNull( newValues[i] ) ) < 0 )
// {
// valueList.add( DEUtil.resolveNull( newValues[i] ) );
// change = true;
// }
// }
// if ( change )
// {
// tableViewer.refresh( );
// updateButtons( );
// addExpressionValue.setFocus( );
// }
//
// }
//
// }
// }
// }
//
// };
private int create2ValueComposite( Composite condition )
{
if ( expressionValue1 != null && !expressionValue1.isDisposed( ) )
{
return 0;
}
if ( valueListComposite != null && !valueListComposite.isDisposed( ) )
{
valueListComposite.dispose( );
valueListComposite = null;
}
GridData expgd = new GridData( GridData.FILL_HORIZONTAL );
expgd.minimumWidth = 100;
expressionValue1 = new ValueCombo( condition, SWT.NONE );
expressionValue1.setLayoutData( expgd );
expressionValue1.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
updateButtons( );
}
} );
// expressionValue1.addListener( SWT.Verify, expValueVerifyListener );
// expressionValue1.addListener( SWT.Selection,
// expValueSelectionListener );
refreshList( );
expressionValue1.setItems( popupItems );
expressionValue1.addSelectionListener( 0, selectValueAction );
expressionValue1.addSelectionListener( 1, expValueAction );
dummy1 = createDummy( condition, 3 );
andLable = new Label( condition, SWT.NONE );
andLable.setText( Messages.getString( "FilterConditionBuilder.text.AND" ) ); //$NON-NLS-1$
andLable.setEnabled( false );
// andLable.setVisible( false );
dummy2 = createDummy( condition, 3 );
expressionValue2 = new ValueCombo( condition, SWT.NONE );
expressionValue2.setLayoutData( expgd );
expressionValue2.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
updateButtons( );
}
} );
// expressionValue2.addListener( SWT.Verify, expValueVerifyListener );
// expressionValue2.addListener( SWT.Selection,
// expValueSelectionListener );
expressionValue2.setItems( popupItems );
expressionValue2.addSelectionListener( 0, selectValueAction );
expressionValue2.addSelectionListener( 1, expValueAction );
// expressionValue2.setVisible( false );
if ( operator.getItemCount( ) > 0
&& operator.getSelectionIndex( ) == -1 )
{
operator.select( 0 );
operatorChange( );
}
condition.getParent( ).layout( true, true );
if ( getButtonBar( ) != null )
condition.getShell( ).pack( );
return 1;
}
private int createValueListComposite( Composite parent )
{
if ( valueListComposite != null && !valueListComposite.isDisposed( ) )
{
return 0;
}
if ( expressionValue1 != null && !expressionValue1.isDisposed( ) )
{
expressionValue1.dispose( );
expressionValue1 = null;
dummy1.dispose( );
dummy1 = null;
expressionValue2.dispose( );
expressionValue2 = null;
dummy2.dispose( );
dummy2 = null;
andLable.dispose( );
andLable = null;
}
valueListComposite = new Composite( parent, SWT.NONE );
GridData gdata = new GridData( GridData.FILL_BOTH );
gdata.horizontalSpan = 4;
valueListComposite.setLayoutData( gdata );
GridLayout layout = new GridLayout( );
layout.numColumns = 4;
valueListComposite.setLayout( layout );
Group group = new Group( valueListComposite, SWT.NONE );
GridData data = new GridData( GridData.FILL_BOTH );
data.horizontalSpan = 3;
data.horizontalIndent = 0;
data.grabExcessHorizontalSpace = true;
group.setLayoutData( data );
layout = new GridLayout( );
layout.numColumns = 4;
group.setLayout( layout );
new Label( group, SWT.NONE ).setText( Messages.getString( "FilterConditionBuilder.label.value" ) ); //$NON-NLS-1$
GridData expgd = new GridData( );
expgd.widthHint = 100;
addExpressionValue = new MultiValueCombo( group, SWT.NONE );
addExpressionValue.setLayoutData( expgd );
addBtn = new Button( group, SWT.PUSH );
addBtn.setText( Messages.getString( "FilterConditionBuilder.button.add" ) ); //$NON-NLS-1$
addBtn.setToolTipText( Messages.getString( "FilterConditionBuilder.button.add.tooltip" ) ); //$NON-NLS-1$
setButtonLayoutData( addBtn );
addBtn.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
String value = addExpressionValue.getText( ).trim( );
if ( valueList.indexOf( value ) < 0 )
{
valueList.add( value );
tableViewer.refresh( );
updateButtons( );
addExpressionValue.setFocus( );
addExpressionValue.setText( "" ); //$NON-NLS-1$
}
else
{
addBtn.setEnabled( false );
}
}
} );
new Label( group, SWT.NONE );
int tableStyle = SWT.SINGLE
| SWT.BORDER
| SWT.H_SCROLL
| SWT.V_SCROLL
| SWT.FULL_SELECTION;
table = new Table( group, tableStyle );
data = new GridData( GridData.FILL_BOTH );
data.horizontalSpan = 4;
table.setLayoutData( data );
table.setHeaderVisible( false );
table.setLinesVisible( true );
TableColumn column;
int i;
String[] columNames = new String[]{
Messages.getString( "FilterConditionBuilder.list.item1" ), //$NON-NLS-1$
};
int[] columLength = new int[]{
288
};
for ( i = 0; i < columNames.length; i++ )
{
column = new TableColumn( table, SWT.NONE, i );
column.setText( columNames[i] );
column.setWidth( columLength[i] );
}
table.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
checkEditDelButtonStatus( );
}
} );
table.addKeyListener( new KeyListener( ) {
public void keyPressed( KeyEvent e )
{
if ( e.keyCode == SWT.DEL )
{
delTableValue( );
}
}
public void keyReleased( KeyEvent e )
{
}
} );
table.addMouseListener( new MouseAdapter( ) {
public void mouseDoubleClick( MouseEvent e )
{
editTableValue( );
}
} );
tableViewer = new TableViewer( table );
tableViewer.setUseHashlookup( true );
tableViewer.setColumnProperties( columNames );
tableViewer.setLabelProvider( tableLableProvier );
tableViewer.setContentProvider( tableContentProvider );
Composite rightPart = new Composite( valueListComposite, SWT.NONE );
data = new GridData( GridData.HORIZONTAL_ALIGN_END );
rightPart.setLayoutData( data );
layout = new GridLayout( );
layout.makeColumnsEqualWidth = true;
rightPart.setLayout( layout );
editBtn = new Button( rightPart, SWT.PUSH );
editBtn.setText( Messages.getString( "FilterConditionBuilder.button.edit" ) ); //$NON-NLS-1$
editBtn.setToolTipText( Messages.getString( "FilterConditionBuilder.button.edit.tooltip" ) ); //$NON-NLS-1$
setButtonLayoutData( editBtn );
GridData gd = (GridData) editBtn.getLayoutData( );
gd.grabExcessVerticalSpace = true;
gd.verticalAlignment = SWT.END;
editBtn.setLayoutData( gd );
editBtn.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
editTableValue( );
}
} );
delBtn = new Button( rightPart, SWT.PUSH );
delBtn.setText( Messages.getString( "FilterConditionBuilder.button.delete" ) ); //$NON-NLS-1$
delBtn.setToolTipText( Messages.getString( "FilterConditionBuilder.button.delete.tooltip" ) ); //$NON-NLS-1$
setButtonLayoutData( delBtn );
delBtn.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
delTableValue( );
}
} );
delAllBtn = new Button( rightPart, SWT.PUSH );
delAllBtn.setText( Messages.getString( "FilterConditionBuilder.button.deleteall" ) ); //$NON-NLS-1$
delAllBtn.setToolTipText( Messages.getString( "FilterConditionBuilder.button.deleteall.tooltip" ) ); //$NON-NLS-1$
setButtonLayoutData( delAllBtn );
gd = (GridData) delAllBtn.getLayoutData( );
gd.grabExcessVerticalSpace = true;
gd.verticalAlignment = SWT.BEGINNING;
delAllBtn.setLayoutData( gd );
delAllBtn.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
int count = valueList.size( );
if ( count > 0 )
{
valueList.clear( );
tableViewer.refresh( );
updateButtons( );
}
else
{
delAllBtn.setEnabled( false );
}
}
} );
addExpressionValue.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkAddButtonStatus( );
updateButtons( );
}
} );
// addExpressionValue.addListener( SWT.Verify, expValueVerifyListener );
// addExpressionValue.addListener( SWT.Selection,
// expValueSelectionListener );
refreshList( );
addExpressionValue.setItems( popupItems );
addExpressionValue.addSelectionListener( 0, mAddSelValueAction );
addExpressionValue.addSelectionListener( 1, mAddExpValueAction );
parent.getParent( ).layout( true, true );
if ( getButtonBar( ) != null )
parent.getShell( ).pack( );
return 1;
}
protected ITableLabelProvider tableLableProvier = new ITableLabelProvider( ) {
public Image getColumnImage( Object element, int columnIndex )
{
return null;
}
public String getColumnText( Object element, int columnIndex )
{
if ( columnIndex == 0 )
{
if ( element instanceof Expression )
{
return ( (Expression) element ).getStringExpression( );
}
return element.toString( );
}
return ""; //$NON-NLS-1$
}
public void addListener( ILabelProviderListener listener )
{
}
public void dispose( )
{
}
public boolean isLabelProperty( Object element, String property )
{
return false;
}
public void removeListener( ILabelProviderListener listener )
{
}
};
protected IStructuredContentProvider tableContentProvider = new IStructuredContentProvider( ) {
public void dispose( )
{
}
public void inputChanged( Viewer viewer, Object oldInput,
Object newInput )
{
}
public Object[] getElements( Object inputElement )
{
if ( inputElement == null )
{
return new Object[0];
}
else if ( inputElement instanceof List )
{
return ( (List) inputElement ).toArray( );
}
return null;
}
};
protected void operatorChange( )
{
String value = getValueForOperator( operator.getText( ) );
valueVisible = determineValueVisible( value );
if ( valueVisible == 3 )
{
int ret = createValueListComposite( operator.getParent( ) );
if ( ret != 0 )
{
if ( filterCondition != null )
{
valueList = new ArrayList( filterCondition.getValue1List( ) );
}
tableViewer.setInput( valueList );
}
}
else
{
int ret = create2ValueComposite( operator.getParent( ) );
if ( ret != 0 && filterCondition != null )
{
expressionValue1.setText( DEUtil.resolveNull( filterCondition.getValue1( ) ) );
expressionValue2.setText( DEUtil.resolveNull( filterCondition.getValue2( ) ) );
}
}
if ( valueVisible == 0 )
{
expressionValue1.setVisible( false );
expressionValue2.setVisible( false );
andLable.setVisible( false );
}
else if ( valueVisible == 1 )
{
expressionValue1.setVisible( true );
expressionValue2.setVisible( false );
andLable.setVisible( false );
}
else if ( valueVisible == 2 )
{
expressionValue1.setVisible( true );
expressionValue2.setVisible( true );
andLable.setVisible( true );
andLable.setEnabled( true );
}
updateButtons( );
}
protected SelectionListener operatorSelection = new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
operatorChange( );
}
};
protected Object getResultSetColumn( String name )
{
if ( columnList.isEmpty( ) )
{
return null;
}
for ( int i = 0; i < columnList.size( ); i++ )
{
if ( getColumnName( columnList.get( i ) ).equals( name ) )
{
return columnList.get( i );
}
}
return null;
}
protected Composite createDummy( Composite parent, int colSpan )
{
Composite dummy = new Composite( parent, SWT.NONE );
GridData gdata = new GridData( );
gdata.widthHint = 22;
gdata.horizontalSpan = colSpan;
gdata.heightHint = 10;
dummy.setLayoutData( gdata );
return dummy;
}
/*
* Update handle for the Map Rule builder
*/
public void updateHandle( FilterConditionHandle handle, int handleCount )
{
this.filterCondition = handle;
}
/*
* Set design handle for the Map Rule builder
*/
public void setDesignHandle( DesignElementHandle handle )
{
this.designHandle = handle;
setColumnList( this.designHandle );
}
/*
* If set dataset handle , then the priority of the dataset is first.
*/
public void setDataSetHandle( DataSetHandle handle )
{
this.dataSetHandle = handle;
setColumnList( this.dataSetHandle );
}
public void setDataSetHandle( DataSetHandle handle,
IExpressionProvider provider )
{
setDataSetHandle( handle );
this.expressionProvider = provider;
}
protected IExpressionProvider expressionProvider;
public void setDesignHandle( DesignElementHandle handle,
IExpressionProvider provider )
{
setDesignHandle( handle );
this.expressionProvider = provider;
setColumnList( this.designHandle );
}
private DataSetHandle dataset;
protected void setColumnList( DesignElementHandle handle )
{
if ( handle instanceof DataSetHandle )
{
dataset = (DataSetHandle) handle;
try
{
columnList = DataUtil.getColumnList( dataset );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
else if ( handle instanceof TabularCubeHandle
|| handle instanceof TabularHierarchyHandle )
{
try
{
if ( handle instanceof TabularCubeHandle )
dataset = ( (TabularCubeHandle) handle ).getDataSet( );
else
{
dataset = ( (TabularHierarchyHandle) handle ).getDataSet( );
if ( dataset == null
&& ( (TabularHierarchyHandle) handle ).getLevelCount( ) > 0 )
{
dataset = ( (TabularCubeHandle) ( (TabularHierarchyHandle) handle ).getContainer( )
.getContainer( ) ).getDataSet( );
}
}
if ( dataset != null )
columnList = DataUtil.getColumnList( dataset );
else
columnList = Collections.EMPTY_LIST;
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
else
{
columnList = DEUtil.getVisiableColumnBindingsList( handle );
}
}
/*
* Return the hanle of Map Rule builder
*/
public FilterConditionHandle getInputHandle( )
{
return filterCondition;
}
/**
* Refreshes the OK button state.
*
*/
protected void updateButtons( )
{
enableInput( isExpressionOK( ) );
if ( getButton( IDialogConstants.OK_ID ) != null )
{
getButton( IDialogConstants.OK_ID ).setEnabled( isConditionOK( ) );
}
}
protected void enableInput( boolean val )
{
operator.setEnabled( val );
if ( valueVisible != 3 )
{
if ( expressionValue1 != null )
expressionValue1.setEnabled( val );
if ( expressionValue2 != null )
expressionValue2.setEnabled( val );
if ( andLable != null )
{
andLable.setEnabled( val );
}
}
else
{
setControlEnable( valueListComposite, val );
if ( val )
{
checkAddButtonStatus( );
checkEditDelButtonStatus( );
} // or set all the children control to false
}
}
protected void setControlEnable( Control control, boolean bool )
{
if ( control == null || control.isDisposed( ) )
{
return;
}
control.setEnabled( bool );
Composite tmp = null;
if ( control instanceof Composite )
{
tmp = (Composite) control;
}
if ( tmp != null && tmp.getChildren( ) != null )
{
for ( int i = 0; i < tmp.getChildren( ).length; i++ )
{
setControlEnable( tmp.getChildren( )[i], bool );
}
}
}
/**
* Gets if the expression field is not empty.
*/
protected boolean isExpressionOK( )
{
if ( expression == null )
{
return false;
}
if ( expression.getText( ) == null
|| expression.getText( ).length( ) == 0 )
{
return false;
}
return true;
}
/**
* Gets if the condition is available.
*/
protected boolean isConditionOK( )
{
if ( expression == null )
{
return false;
}
if ( !isExpressionOK( ) )
{
return false;
}
return checkValues( );
}
/**
* Gets if the values of the condition is(are) available.
*/
protected boolean checkValues( )
{
if ( valueVisible == 3 )
{
if ( valueList.size( ) <= 0 )
{
return false;
}
else
{
return true;
}
}
else
{
assert ( !expressionValue1.isDisposed( ) );
assert ( !expressionValue2.isDisposed( ) );
if ( expressionValue1.getVisible( ) )
{
if ( expressionValue1.getText( ) == null
|| expressionValue1.getText( ).trim( ).length( ) == 0 )
{
return false;
}
}
if ( expressionValue2.getVisible( ) )
{
if ( expressionValue2.getText( ) == null
|| expressionValue2.getText( ).trim( ).length( ) == 0 )
{
return false;
}
}
}
return true;
}
protected void checkAddButtonStatus( )
{
if ( addExpressionValue != null )
{
String value = addExpressionValue.getText( );
if ( value == null
|| value.length( ) == 0
|| value.trim( ).length( ) == 0 )
{
addBtn.setEnabled( false );
return;
}
if ( value != null )
{
value = value.trim( );
}
if ( valueList.indexOf( value ) < 0 )
{
addBtn.setEnabled( true );
}
else
{
addBtn.setEnabled( false );
}
}
}
protected void checkEditDelButtonStatus( )
{
if ( tableViewer == null )
{
return;
}
boolean enabled = ( tableViewer.getSelection( ) == null ) ? false
: true;
if ( enabled == true
&& tableViewer.getSelection( ) instanceof StructuredSelection )
{
StructuredSelection selection = (StructuredSelection) tableViewer.getSelection( );
if ( selection.toList( ).size( ) <= 0 )
{
enabled = false;
}
}
editBtn.setEnabled( enabled );
delBtn.setEnabled( enabled );
enabled = table.getItemCount( ) > 0 ? true : false;
delAllBtn.setEnabled( enabled );
}
private void setExpression( )
{
ExpressionButtonUtil.initExpressionButtonControl( expression,
filterCondition,
FilterCondition.EXPR_MEMBER );
}
/**
* SYNC the control value according to the handle.
*/
protected void syncViewProperties( )
{
filterCondition.getProperty( FilterCondition.EXPR_MEMBER );
setExpression( );
operator.select( getIndexForOperatorValue( filterCondition.getOperator( ) ) );
valueVisible = determineValueVisible( filterCondition.getOperator( ) );
if ( valueVisible == 3 )
{
createValueListComposite( operator.getParent( ) );
valueList = new ArrayList( filterCondition.getValue1List( ) );
tableViewer.setInput( valueList );
}
else
{
create2ValueComposite( operator.getParent( ) );
expressionValue1.setText( DEUtil.resolveNull( filterCondition.getValue1( ) ) );
expressionValue2.setText( DEUtil.resolveNull( filterCondition.getValue2( ) ) );
}
if ( valueVisible == 0 )
{
expressionValue1.setVisible( false );
expressionValue2.setVisible( false );
andLable.setVisible( false );
}
else if ( valueVisible == 1 )
{
expressionValue1.setVisible( true );
expressionValue2.setVisible( false );
andLable.setVisible( false );
}
else if ( valueVisible == 2 )
{
expressionValue1.setVisible( true );
expressionValue2.setVisible( true );;
andLable.setVisible( true );
andLable.setEnabled( true );
}
else if ( valueVisible == 3 )
{
if ( expression.getText( ).length( ) == 0 )
{
valueListComposite.setEnabled( false );
}
else
{
valueListComposite.setEnabled( true );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
protected void okPressed( )
{
try
{
if ( filterCondition == null )
{
FilterCondition filter = StructureFactory.createFilterCond( );
filter.setProperty( FilterCondition.OPERATOR_MEMBER,
DEUtil.resolveNull( getValueForOperator( operator.getText( ) ) ) );
if ( valueVisible == 3 )
{
filter.setValue1( valueList );
filter.setValue2( "" ); //$NON-NLS-1$
}
else
{
assert ( !expressionValue1.isDisposed( ) );
assert ( !expressionValue2.isDisposed( ) );
if ( expressionValue1.getVisible( ) )
{
filter.setValue1( DEUtil.resolveNull( expressionValue1.getText( ) ) );
}
else
{
filter.setValue1( NULL_STRING );
}
if ( expressionValue2.getVisible( ) )
{
filter.setValue2( DEUtil.resolveNull( expressionValue2.getText( ) ) );
}
}
// set test expression for new map rule
ExpressionButtonUtil.saveExpressionButtonControl( expression,
filter,
FilterCondition.EXPR_MEMBER );
if ( dataSetHandle != null )
{
PropertyHandle propertyHandle = dataSetHandle.getPropertyHandle( ListingHandle.FILTER_PROP );
propertyHandle.addItem( filter );
}
else
{
PropertyHandle propertyHandle = designHandle.getPropertyHandle( ListingHandle.FILTER_PROP );
propertyHandle.addItem( filter );
}
}
else
{
filterCondition.setOperator( DEUtil.resolveNull( getValueForOperator( operator.getText( ) ) ) );
if ( valueVisible == 3 )
{
filterCondition.setValue1( valueList );
filterCondition.setValue2( NULL_STRING );
}
else
{
assert ( !expressionValue1.isDisposed( ) );
assert ( !expressionValue2.isDisposed( ) );
if ( expressionValue1.getVisible( ) )
{
filterCondition.setValue1( DEUtil.resolveNull( expressionValue1.getText( ) ) );
}
else
{
filterCondition.setValue1( NULL_STRING );
}
if ( expressionValue2.getVisible( ) )
{
filterCondition.setValue2( DEUtil.resolveNull( expressionValue2.getText( ) ) );
}
else
{
filterCondition.setValue2( NULL_STRING );
}
}
ExpressionButtonUtil.saveExpressionButtonControl( expression,
filterCondition,
FilterCondition.EXPR_MEMBER );
}
}
catch ( Exception e )
{
ExceptionUtil.handle( e );
}
super.okPressed( );
}
protected void editValue( Control control )
{
String initValue = null;
if ( control instanceof Text )
{
initValue = ( (Text) control ).getText( );
}
else if ( control instanceof Combo )
{
initValue = ( (Combo) control ).getText( );
}
ExpressionBuilder expressionBuilder = new ExpressionBuilder( getShell( ),
initValue );
setProviderForExpressionBuilder( expressionBuilder );
if ( expressionBuilder.open( ) == OK )
{
String result = DEUtil.resolveNull( expressionBuilder.getResult( ) );
if ( control instanceof Text )
{
( (Text) control ).setText( result );
}
else if ( control instanceof Combo )
{
( (Combo) control ).setText( result );
}
}
updateButtons( );
}
private void setProviderForExpressionBuilder(
ExpressionBuilder expressionBuilder )
{
if ( dataSetHandle != null )
{
if ( expressionProvider == null )
{
expressionBuilder.setExpressionProvier( new ExpressionProvider( dataSetHandle ) );
}
else
{
expressionBuilder.setExpressionProvier( expressionProvider );
}
}
else if ( designHandle != null )
{
if ( expressionProvider == null )
{
if ( designHandle instanceof TabularCubeHandle
|| designHandle instanceof TabularHierarchyHandle )
{
expressionBuilder.setExpressionProvier( new BindingExpressionProvider( designHandle,
null ) );
}
else
{
expressionBuilder.setExpressionProvier( new ExpressionProvider( designHandle ) );
}
}
else
{
expressionBuilder.setExpressionProvier( expressionProvider );
}
}
}
/**
* Sets the model input.
*
* @param sortKey
*/
public void setInput( Object inputHandle )
{
if ( inputHandle instanceof FilterConditionHandle )
{
this.filterCondition = (FilterConditionHandle) inputHandle;
}
else
{
this.filterCondition = null;
}
}
private void refreshList( )
{
if ( refreshItems )
{
ArrayList finalItems = new ArrayList( 10 );
for ( int n = 0; n < actions.length; n++ )
{
finalItems.add( actions[n] );
}
if ( currentItem != null )
{
// addParamterItems( finalItems );
}
popupItems = (String[]) finalItems.toArray( EMPTY_ARRAY );
}
refreshItems = false;
}
private List getSelectValueList( ) throws BirtException
{
List selectValueList = new ArrayList( );
ReportItemHandle reportItem = DEUtil.getBindingHolder( currentItem );
if ( bindingName != null && reportItem != null )
{
selectValueList = SelectValueFetcher.getSelectValueList( expression.getText( ),
reportItem.getDataSet( ),
false );
}
else
{
ExceptionHandler.openErrorMessageBox( Messages.getString( "SelectValueDialog.errorRetrievinglist" ), Messages.getString( "SelectValueDialog.noExpressionSet" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
return selectValueList;
}
public int open( )
{
if ( getShell( ) == null )
{
// create the window
create( );
}
updateButtons( );
return super.open( );
}
protected ValueCombo.ISelection selectValueAction = new ValueCombo.ISelection( ) {
public String doSelection( String input )
{
String retValue = null;
if ( dataSetHandle != null
|| designHandle instanceof TabularCubeHandle
|| designHandle instanceof TabularHierarchyHandle )
{
DataSetHandle dataSet = null;
if ( dataSetHandle != null )
{
dataSet = dataSetHandle;
}
else
{
if ( designHandle instanceof TabularCubeHandle )
{
dataSet = ( (TabularCubeHandle) designHandle ).getDataSet( );
}
else
{
dataSet = ( (TabularHierarchyHandle) designHandle ).getDataSet( );
}
}
String expressionString = expression.getText( );
try
{
List selectValueList = SelectValueFetcher.getSelectValueList( expressionString,
dataSet );
SelectValueDialog dialog = new SelectValueDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
dialog.setSelectedValueList( selectValueList );
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
retValue = dialog.getSelectedExprValue( );
}
}
catch ( BirtException e1 )
{
MessageDialog.openError( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
+ "\n" //$NON-NLS-1$
+ e1.getMessage( ) );
}
}
else
{
for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); )
{
String columnName = getColumnName( iter.next( ) );
if ( DEUtil.getColumnExpression( columnName )
.equals( expression.getText( ) ) )
{
bindingName = columnName;
break;
}
}
if ( bindingName != null )
{
try
{
List selectValueList = getSelectValueList( );
SelectValueDialog dialog = new SelectValueDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
dialog.setSelectedValueList( selectValueList );
if ( bindingParams != null )
{
dialog.setBindingParams( bindingParams );
}
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
retValue = dialog.getSelectedExprValue( );
}
}
catch ( Exception ex )
{
MessageDialog.openError( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
+ "\n" //$NON-NLS-1$
+ ex.getMessage( ) );
}
}
else
{
MessageDialog.openInformation( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.info.selectVauleUnavailable" ) ); //$NON-NLS-1$
}
}
return retValue;
}
};
protected ValueCombo.ISelection expValueAction = new ValueCombo.ISelection( ) {
public String doSelection( String input )
{
String retValue = null;
ExpressionBuilder dialog = new ExpressionBuilder( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
input );
if ( expressionProvider == null )
dialog.setExpressionProvider( new ExpressionProvider( designHandle ) );
else
dialog.setExpressionProvider( expressionProvider );
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
retValue = dialog.getResult( );
}
return retValue;
}
};
protected MultiValueCombo.ISelection mAddExpValueAction = new MultiValueCombo.ISelection( ) {
public String[] doSelection( String input )
{
String[] retValue = null;
ExpressionBuilder dialog = new ExpressionBuilder( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
input );
if ( expressionProvider == null )
dialog.setExpressionProvider( new ExpressionProvider( designHandle ) );
else
dialog.setExpressionProvider( expressionProvider );
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
if ( dialog.getResult( ).length( ) != 0 )
{
retValue = new String[]{
dialog.getResult( )
};
}
}
return retValue;
}
public void doAfterSelection( MultiValueCombo combo )
{
mAddSelValueAction.doAfterSelection( combo );
}
};
protected MultiValueCombo.ISelection mAddSelValueAction = new MultiValueCombo.ISelection( ) {
public String[] doSelection( String input )
{
String[] retValue = null;
if ( dataSetHandle != null
|| designHandle instanceof TabularCubeHandle
|| designHandle instanceof TabularHierarchyHandle )
{
DataSetHandle dataSet;
if ( dataSetHandle != null )
{
dataSet = dataSetHandle;
}
else
{
if ( designHandle instanceof TabularCubeHandle )
dataSet = ( (TabularCubeHandle) designHandle ).getDataSet( );
else
{
dataSet = ( (TabularHierarchyHandle) designHandle ).getDataSet( );
if ( dataSet == null
&& ( (TabularHierarchyHandle) designHandle ).getLevelCount( ) > 0 )
{
dataSet = ( (TabularCubeHandle) ( (TabularHierarchyHandle) designHandle ).getContainer( )
.getContainer( ) ).getDataSet( );
}
}
}
String expressionString = expression.getText( );
try
{
List selectValueList = SelectValueFetcher.getSelectValueList( expressionString,
dataSet );
SelectValueDialog dialog = new SelectValueDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
dialog.setSelectedValueList( selectValueList );
dialog.setMultipleSelection( true );
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
retValue = dialog.getSelectedExprValues( );
}
}
catch ( BirtException e1 )
{
MessageDialog.openError( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
+ "\n" //$NON-NLS-1$
+ e1.getMessage( ) );
}
}
else
{
for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); )
{
Object obj = iter.next( );
String columnName = Messages.getString( "ExpressionValueCellEditor.title" ); //$NON-NLS-1$
if ( obj instanceof ComputedColumnHandle )
{
columnName = ( (ComputedColumnHandle) ( obj ) ).getName( );
}
else if ( obj instanceof ResultSetColumnHandle )
{
columnName = ( (ResultSetColumnHandle) ( obj ) ).getColumnName( );
}
if ( DEUtil.getColumnExpression( columnName )
.equals( expression.getText( ) ) )
{
bindingName = columnName;
break;
}
}
if ( bindingName != null )
{
try
{
List selectValueList = getSelectValueList( );
SelectValueDialog dialog = new SelectValueDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
dialog.setMultipleSelection( true );
dialog.setSelectedValueList( selectValueList );
if ( bindingParams != null )
{
dialog.setBindingParams( bindingParams );
}
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
retValue = dialog.getSelectedExprValues( );
}
}
catch ( Exception ex )
{
MessageDialog.openError( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
+ "\n" //$NON-NLS-1$
+ ex.getMessage( ) );
}
}
else
{
MessageDialog.openInformation( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.info.selectVauleUnavailable" ) ); //$NON-NLS-1$
}
}
return retValue;
}
public void doAfterSelection( MultiValueCombo combo )
{
addBtn.setEnabled( false );
if ( addExpressionValue.getSelStrings( ).length == 1 )
{
addExpressionValue.setText( DEUtil.resolveNull( addExpressionValue.getSelStrings( )[0] ) );
}
else if ( addExpressionValue.getSelStrings( ).length > 1 )
{
addExpressionValue.setText( "" ); //$NON-NLS-1$
}
boolean change = false;
for ( int i = 0; i < addExpressionValue.getSelStrings( ).length; i++ )
{
if ( valueList.indexOf( DEUtil.resolveNull( addExpressionValue.getSelStrings( )[i] ) ) < 0 )
{
valueList.add( DEUtil.resolveNull( addExpressionValue.getSelStrings( )[i] ) );
change = true;
}
}
if ( change )
{
tableViewer.refresh( );
updateButtons( );
addExpressionValue.setFocus( );
}
}
};
protected void editTableValue( )
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection( );
if ( selection.getFirstElement( ) != null
&& selection.getFirstElement( ) instanceof String )
{
String initValue = (String) selection.getFirstElement( );
ExpressionBuilder expressionBuilder = new ExpressionBuilder( getShell( ),
initValue );
if ( designHandle != null )
{
if ( expressionProvider == null )
{
if ( designHandle instanceof TabularCubeHandle
|| designHandle instanceof TabularHierarchyHandle )
{
expressionBuilder.setExpressionProvider( new BindingExpressionProvider( designHandle,
null ) );
}
else
{
expressionBuilder.setExpressionProvider( new ExpressionProvider( designHandle ) );
}
}
else
{
expressionBuilder.setExpressionProvider( expressionProvider );
}
}
if ( expressionBuilder.open( ) == OK )
{
String result = DEUtil.resolveNull( expressionBuilder.getResult( ) );
if ( result.length( ) == 0 )
{
MessageDialog.openInformation( getShell( ),
Messages.getString( "MapRuleBuilderDialog.MsgDlg.Title" ), //$NON-NLS-1$
Messages.getString( "MapRuleBuilderDialog.MsgDlg.Msg" ) ); //$NON-NLS-1$
return;
}
int index = table.getSelectionIndex( );
valueList.remove( index );
valueList.add( index, result );
tableViewer.refresh( );
table.select( index );
}
updateButtons( );
}
else
{
editBtn.setEnabled( false );
}
}
protected void delTableValue( )
{
int index = table.getSelectionIndex( );
if ( index > -1 )
{
valueList.remove( index );
tableViewer.refresh( );
if ( valueList.size( ) > 0 )
{
if ( valueList.size( ) <= index )
{
index = index - 1;
}
table.select( index );
}
updateButtons( );
}
else
{
delBtn.setEnabled( false );
}
}
} | UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/dialogs/FilterConditionBuilder.java | /*******************************************************************************
* Copyright (c) 2004, 2008 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.dialogs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.designer.data.ui.util.SelectValueFetcher;
import org.eclipse.birt.report.designer.internal.ui.expressions.IExpressionConverter;
import org.eclipse.birt.report.designer.internal.ui.swt.custom.MultiValueCombo;
import org.eclipse.birt.report.designer.internal.ui.swt.custom.ValueCombo;
import org.eclipse.birt.report.designer.internal.ui.util.DataUtil;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.ExpressionButtonUtil;
import org.eclipse.birt.report.designer.internal.ui.util.ExpressionUtility;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.util.ExceptionUtil;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.designer.util.AlphabeticallyComparator;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.Expression;
import org.eclipse.birt.report.model.api.FilterConditionHandle;
import org.eclipse.birt.report.model.api.ListingHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.FilterCondition;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.metadata.IChoiceSet;
import org.eclipse.birt.report.model.api.olap.TabularCubeHandle;
import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
/**
* Dialog for adding or editing map rule.
*/
public class FilterConditionBuilder extends BaseTitleAreaDialog
{
protected static Logger logger = Logger.getLogger( FilterConditionBuilder.class.getName( ) );
public static final String DLG_TITLE_NEW = Messages.getString( "FilterConditionBuilder.DialogTitle.New" ); //$NON-NLS-1$
public static final String DLG_TITLE_EDIT = Messages.getString( "FilterConditionBuilder.DialogTitle.Edit" ); //$NON-NLS-1$
public static final String DLG_MESSAGE_NEW = Messages.getString( "FilterConditionBuilder.DialogMessage.New" ); //$NON-NLS-1$
public static final String DLG_MESSAGE_EDIT = Messages.getString( "FilterConditionBuilder.DialogMessage.Edit" ); //$NON-NLS-1$
protected transient String[] popupItems = null;
private static String[] actions = new String[]{
Messages.getString( "ExpressionValueCellEditor.selectValueAction" ), //$NON-NLS-1$
Messages.getString( "ExpressionValueCellEditor.buildExpressionAction" ), //$NON-NLS-1$
};
protected final String NULL_STRING = null;
protected Composite dummy1, dummy2;
protected Label label1, label2;
protected List valueList = new ArrayList( );
protected List selValueList = new ArrayList( );
/**
* Usable operators for building map rule conditions.
*/
protected static final String[][] OPERATOR;
private transient String bindingName;
private ParamBindingHandle[] bindingParams = null;
private transient boolean refreshItems = true;
protected transient ReportElementHandle currentItem = null;
protected static final String[] EMPTY_ARRAY = new String[]{};
protected List columnList;
protected int valueVisible;
protected Table table;
protected TableViewer tableViewer;
/**
* Constant, represents empty String array.
*/
protected static final String[] EMPTY = new String[0];
public void setReportElement( ReportElementHandle reportItem )
{
currentItem = reportItem;
}
/**
* @param bindingName
* The selectValueExpression to set.
*/
public void setBindingName( String bindingName )
{
this.bindingName = bindingName;
}
/**
*
*/
public void setBindingParams( ParamBindingHandle[] params )
{
this.bindingParams = params;
}
/**
* @param title
*/
public FilterConditionBuilder( String title, String message )
{
this( UIUtil.getDefaultShell( ), title, message );
}
protected String title, message;
protected IChoiceSet choiceSet;
/**
* @param parentShell
* @param title
*/
public FilterConditionBuilder( Shell parentShell, String title,
String message )
{
super( parentShell );
this.title = title;
this.message = message;
}
static
{
IChoiceSet chset = ChoiceSetFactory.getStructChoiceSet( FilterCondition.FILTER_COND_STRUCT,
FilterCondition.OPERATOR_MEMBER );
IChoice[] chs = chset.getChoices( new AlphabeticallyComparator( ) );
OPERATOR = new String[chs.length][2];
for ( int i = 0; i < chs.length; i++ )
{
OPERATOR[i][0] = chs[i].getDisplayName( );
OPERATOR[i][1] = chs[i].getName( );
}
}
/**
* Returns the operator value by its display name.
*
* @param name
*/
public static String getValueForOperator( String name )
{
for ( int i = 0; i < OPERATOR.length; i++ )
{
if ( OPERATOR[i][0].equals( name ) )
{
return OPERATOR[i][1];
}
}
return null;
}
/**
* Returns how many value fields this operator needs.
*
* @param operatorValue
*/
public static int determineValueVisible( String operatorValue )
{
if ( DesignChoiceConstants.FILTER_OPERATOR_ANY.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_FALSE.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_TRUE.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_NULL.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_NOT_NULL.equals( operatorValue ) )
{
return 0;
}
else if ( DesignChoiceConstants.FILTER_OPERATOR_LT.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_LE.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_EQ.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_NE.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_GE.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_GT.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_LIKE.equals( operatorValue ) )
{
return 1;
}
else if ( DesignChoiceConstants.FILTER_OPERATOR_BETWEEN.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_NOT_BETWEEN.equals( operatorValue ) )
{
return 2;
}
else if ( DesignChoiceConstants.FILTER_OPERATOR_IN.equals( operatorValue )
|| DesignChoiceConstants.FILTER_OPERATOR_NOT_IN.equals( operatorValue ) )
{
return 3;
}
return 1;
}
/**
* Returns the operator display name by its value.
*
* @param value
*/
public static String getNameForOperator( String value )
{
for ( int i = 0; i < OPERATOR.length; i++ )
{
if ( OPERATOR[i][1].equals( value ) )
{
return OPERATOR[i][0];
}
}
return ""; //$NON-NLS-1$
}
/**
* Returns the index for given operator value in the operator list.
*
* @param value
*/
protected static int getIndexForOperatorValue( String value )
{
for ( int i = 0; i < OPERATOR.length; i++ )
{
if ( OPERATOR[i][1].equals( value ) )
{
return i;
}
}
return 0;
}
protected FilterConditionHandle filterCondition;
protected Combo expression, operator;
protected Button addBtn, editBtn, delBtn, delAllBtn;
protected ValueCombo expressionValue1, expressionValue2;
protected MultiValueCombo addExpressionValue;
protected Composite valueListComposite;
protected Label andLable;
protected DesignElementHandle designHandle;
protected DataSetHandle dataSetHandle;
protected String[] getDataSetColumns( )
{
if ( columnList.isEmpty( ) )
{
return EMPTY;
}
String[] values = new String[columnList.size( )];
for ( int i = 0; i < columnList.size( ); i++ )
{
values[i] = getColumnName( columnList.get( i ) );
}
return values;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.dialogs.Dialog#createContents(org.eclipse.swt.widgets
* .Composite)
*/
protected Control createDialogArea( Composite parent )
{
UIUtil.bindHelp( parent,
IHelpContextIds.INSERT_EDIT_FILTER_CONDITION_DIALOG_ID );
Composite area = (Composite) super.createDialogArea( parent );
Composite contents = new Composite( area, SWT.NONE );
contents.setLayoutData( new GridData( GridData.FILL_BOTH ) );
contents.setLayout( new GridLayout( ) );
this.setTitle( title );
this.setMessage( message );
getShell( ).setText( title );
applyDialogFont( contents );
initializeDialogUnits( area );
createFilterConditionContent( contents );
return area;
}
protected void createFilterConditionContent( Composite innerParent )
{
Composite anotherParent = new Composite( innerParent, SWT.NONE );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
anotherParent.setLayoutData( gd );
GridLayout glayout = new GridLayout( 4, false );
anotherParent.setLayout( glayout );
Label lb = new Label( anotherParent, SWT.NONE );
lb.setText( Messages.getString( "FilterConditionBuilder.text.Condition" ) ); //$NON-NLS-1$
Label lb2 = new Label( anotherParent, SWT.NONE );
lb2.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
new Label( anotherParent, SWT.NONE );
Composite condition = new Composite( innerParent, SWT.NONE );
gd = new GridData( GridData.FILL_BOTH );
gd.heightHint = 220;
condition.setLayoutData( gd );
glayout = new GridLayout( 4, false );
condition.setLayout( glayout );
expression = new Combo( condition, SWT.NONE );
GridData gdata = new GridData( );
gdata.widthHint = 100;
expression.setLayoutData( gdata );
expression.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
IExpressionConverter converter = ExpressionButtonUtil.getCurrentExpressionConverter( expression );
if ( converter != null )
{
if ( expression.getSelectionIndex( ) >= 0 )
{
String newValue = expression.getItem( expression.getSelectionIndex( ) );
String value = ExpressionUtility.getColumnExpression( newValue,
converter );
if ( value != null )
newValue = value;
expression.setText( newValue );
}
}
updateButtons( );
}
} );
expression.setItems( getDataSetColumns( ) );
if ( expression.getItemCount( ) == 0 )
{
expression.add( DEUtil.resolveNull( null ) );
}
expression.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
updateButtons( );
}
} );
Listener listener = new Listener( ) {
public void handleEvent( Event event )
{
updateButtons( );
}
};
ExpressionButtonUtil.createExpressionButton( condition,
expression,
getExpressionProvider( ),
designHandle,
listener );
operator = new Combo( condition, SWT.READ_ONLY );
for ( int i = 0; i < OPERATOR.length; i++ )
{
operator.add( OPERATOR[i][0] );
}
operator.addSelectionListener( operatorSelection );
create2ValueComposite( condition );
if ( filterCondition != null )
{
syncViewProperties( );
}
lb = new Label( innerParent, SWT.SEPARATOR | SWT.HORIZONTAL );
lb.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
private IExpressionProvider getExpressionProvider( )
{
IExpressionProvider provider = null;
if ( expressionProvider == null )
{
if ( designHandle instanceof TabularCubeHandle
|| designHandle instanceof TabularHierarchyHandle )
{
provider = new BindingExpressionProvider( designHandle, null );
}
else
{
provider = new ExpressionProvider( designHandle );
}
}
else
{
provider = expressionProvider;
}
return provider;
}
// protected Listener expValueVerifyListener = new Listener( ) {
//
// public void handleEvent( Event event )
// {
// // TODO Auto-generated method stub
// Combo thisCombo = (Combo) event.widget;
// String text = event.text;
// if ( text != null && thisCombo.indexOf( text ) >= 0 )
// {
// event.doit = false;
// }
// else
// {
// event.doit = true;
// }
// }
// };
protected String getColumnName( Object obj )
{
if ( obj instanceof ComputedColumnHandle )
return ( (ComputedColumnHandle) obj ).getName( );
else if ( obj instanceof ResultSetColumnHandle )
return ( (ResultSetColumnHandle) obj ).getColumnName( );
else
return ""; //$NON-NLS-1$
}
// private Listener expValueSelectionListener = new Listener( ) {
//
// public void handleEvent( Event event )
// {
// // TODO Auto-generated method stub
// Combo thisCombo = (Combo) event.widget;
// int selectionIndex = thisCombo.getSelectionIndex( );
// if ( selectionIndex < 0 )
// {
// return;
// }
// String value = popupItems[selectionIndex];
//
// boolean isAddClick = false;
// if ( tableViewer != null
// && ( addBtn != null && ( !addBtn.isDisposed( ) ) ) )
// {
// isAddClick = true;
// }
//
// bindingName = null;
// for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); )
// {
// String columnName = getColumnName( iter.next( ) );
// if ( DEUtil.getColumnExpression( columnName )
// .equals( expression.getText( ) ) )
// {
// bindingName = columnName;
// break;
// }
// }
//
// boolean returnValue = false;
// if ( value != null )
// {
// String newValues[] = new String[1];
// if ( value.equals( ( actions[0] ) ) )
// {
// if ( bindingName != null )
// {
// try
// {
// List selectValueList = getSelectValueList( );
// SelectValueDialog dialog = new SelectValueDialog(
// PlatformUI.getWorkbench( )
// .getDisplay( )
// .getActiveShell( ),
// Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
// if ( isAddClick )
// {
// dialog.setMultipleSelection( true );
// }
// dialog.setSelectedValueList( selectValueList );
// if ( bindingParams != null )
// {
// dialog.setBindingParams( bindingParams );
// }
// if ( dialog.open( ) == IDialogConstants.OK_ID )
// {
// returnValue = true;
// newValues = dialog.getSelectedExprValues( );
// }
// }
// catch ( Exception ex )
// {
// MessageDialog.openError( null,
// Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
// Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
// + "\n" //$NON-NLS-1$
// + ex.getMessage( ) );
// }
// }
// else if ( designHandle instanceof TabularCubeHandle
// || designHandle instanceof TabularHierarchyHandle )
// {
// DataSetHandle dataSet;
// if ( designHandle instanceof TabularCubeHandle )
// dataSet = ( (TabularCubeHandle) designHandle ).getDataSet( );
// else
// {
// dataSet = ( (TabularHierarchyHandle) designHandle ).getDataSet( );
// if ( dataSet == null
// && ( (TabularHierarchyHandle) designHandle ).getLevelCount( ) > 0 )
// {
// dataSet = ( (TabularCubeHandle) ( (TabularHierarchyHandle) designHandle
// ).getContainer( )
// .getContainer( ) ).getDataSet( );
// }
// }
// String expressionString = expression.getText( );
// try
// {
// List selectValueList = SelectValueFetcher.getSelectValueList(
// expressionString,
// dataSet );
// SelectValueDialog dialog = new SelectValueDialog(
// PlatformUI.getWorkbench( )
// .getDisplay( )
// .getActiveShell( ),
// Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
// dialog.setSelectedValueList( selectValueList );
// if ( isAddClick )
// {
// dialog.setMultipleSelection( true );
// }
// if ( dialog.open( ) == IDialogConstants.OK_ID )
// {
// returnValue = true;
// newValues = dialog.getSelectedExprValues( );
//
// }
//
// }
// catch ( BirtException e1 )
// {
// // TODO Auto-generated catch block
// MessageDialog.openError( null,
// Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
// Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
// + "\n" //$NON-NLS-1$
// + e1.getMessage( ) );
// }
// }
// else
// {
// MessageDialog.openInformation( null,
// Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
// Messages.getString( "SelectValueDialog.messages.info.selectVauleUnavailable" ) ); //$NON-NLS-1$
// }
// }
// else if ( value.equals( actions[1] ) )
// {
// ExpressionBuilder dialog = new ExpressionBuilder(
// PlatformUI.getWorkbench( )
// .getDisplay( )
// .getActiveShell( ),
// thisCombo.getText( ) );
//
// if ( designHandle != null )
// {
// if ( expressionProvider == null )
// {
// if ( designHandle instanceof TabularCubeHandle
// || designHandle instanceof TabularHierarchyHandle )
// {
// dialog.setExpressionProvier( new BindingExpressionProvider( designHandle,
// null ) );
// }
// else
// {
// dialog.setExpressionProvier( new ExpressionProvider( designHandle ) );
// }
// }
// else
// {
// dialog.setExpressionProvier( expressionProvider );
// }
// }
//
// if ( dialog.open( ) == IDialogConstants.OK_ID )
// {
// returnValue = true;
// newValues[0] = dialog.getResult( );
// }
// }
// else if ( selectionIndex > 3 )
// {
// newValues[0] = "params[\"" + value + "\"]"; //$NON-NLS-1$ //$NON-NLS-2$
// }
//
// if ( returnValue )
// {
// if ( addExpressionValue == thisCombo )
// {
// thisCombo.setText( "" ); //$NON-NLS-1$
// addBtn.setEnabled( false );
// }
// else if ( newValues.length == 1 )
// {
// thisCombo.setText( DEUtil.resolveNull( newValues[0] ) );
// }
//
// if ( isAddClick )
// {
//
// boolean change = false;
// for ( int i = 0; i < newValues.length; i++ )
// {
// if ( valueList.indexOf( DEUtil.resolveNull( newValues[i] ) ) < 0 )
// {
// valueList.add( DEUtil.resolveNull( newValues[i] ) );
// change = true;
// }
// }
// if ( change )
// {
// tableViewer.refresh( );
// updateButtons( );
// addExpressionValue.setFocus( );
// }
//
// }
//
// }
// }
// }
//
// };
private int create2ValueComposite( Composite condition )
{
if ( expressionValue1 != null && !expressionValue1.isDisposed( ) )
{
return 0;
}
if ( valueListComposite != null && !valueListComposite.isDisposed( ) )
{
valueListComposite.dispose( );
valueListComposite = null;
}
GridData expgd = new GridData( GridData.FILL_HORIZONTAL );
expgd.minimumWidth = 100;
expressionValue1 = new ValueCombo( condition, SWT.NONE );
expressionValue1.setLayoutData( expgd );
expressionValue1.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
updateButtons( );
}
} );
// expressionValue1.addListener( SWT.Verify, expValueVerifyListener );
// expressionValue1.addListener( SWT.Selection,
// expValueSelectionListener );
refreshList( );
expressionValue1.setItems( popupItems );
expressionValue1.addSelectionListener( 0, selectValueAction );
expressionValue1.addSelectionListener( 1, expValueAction );
dummy1 = createDummy( condition, 3 );
andLable = new Label( condition, SWT.NONE );
andLable.setText( Messages.getString( "FilterConditionBuilder.text.AND" ) ); //$NON-NLS-1$
andLable.setEnabled( false );
// andLable.setVisible( false );
dummy2 = createDummy( condition, 3 );
expressionValue2 = new ValueCombo( condition, SWT.NONE );
expressionValue2.setLayoutData( expgd );
expressionValue2.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
updateButtons( );
}
} );
// expressionValue2.addListener( SWT.Verify, expValueVerifyListener );
// expressionValue2.addListener( SWT.Selection,
// expValueSelectionListener );
expressionValue2.setItems( popupItems );
expressionValue2.addSelectionListener( 0, selectValueAction );
expressionValue2.addSelectionListener( 1, expValueAction );
// expressionValue2.setVisible( false );
if ( operator.getItemCount( ) > 0
&& operator.getSelectionIndex( ) == -1 )
{
operator.select( 0 );
operatorChange( );
}
condition.getParent( ).layout( true, true );
if ( getButtonBar( ) != null )
condition.getShell( ).pack( );
return 1;
}
private int createValueListComposite( Composite parent )
{
if ( valueListComposite != null && !valueListComposite.isDisposed( ) )
{
return 0;
}
if ( expressionValue1 != null && !expressionValue1.isDisposed( ) )
{
expressionValue1.dispose( );
expressionValue1 = null;
dummy1.dispose( );
dummy1 = null;
expressionValue2.dispose( );
expressionValue2 = null;
dummy2.dispose( );
dummy2 = null;
andLable.dispose( );
andLable = null;
}
valueListComposite = new Composite( parent, SWT.NONE );
GridData gdata = new GridData( GridData.FILL_BOTH );
gdata.horizontalSpan = 4;
valueListComposite.setLayoutData( gdata );
GridLayout layout = new GridLayout( );
layout.numColumns = 4;
valueListComposite.setLayout( layout );
Group group = new Group( valueListComposite, SWT.NONE );
GridData data = new GridData( GridData.FILL_BOTH );
data.horizontalSpan = 3;
data.horizontalIndent = 0;
data.grabExcessHorizontalSpace = true;
group.setLayoutData( data );
layout = new GridLayout( );
layout.numColumns = 4;
group.setLayout( layout );
new Label( group, SWT.NONE ).setText( Messages.getString( "FilterConditionBuilder.label.value" ) ); //$NON-NLS-1$
GridData expgd = new GridData( );
expgd.widthHint = 100;
addExpressionValue = new MultiValueCombo( group, SWT.NONE );
addExpressionValue.setLayoutData( expgd );
addBtn = new Button( group, SWT.PUSH );
addBtn.setText( Messages.getString( "FilterConditionBuilder.button.add" ) ); //$NON-NLS-1$
addBtn.setToolTipText( Messages.getString( "FilterConditionBuilder.button.add.tooltip" ) ); //$NON-NLS-1$
setButtonLayoutData( addBtn );
addBtn.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
String value = addExpressionValue.getText( ).trim( );
if ( valueList.indexOf( value ) < 0 )
{
valueList.add( value );
tableViewer.refresh( );
updateButtons( );
addExpressionValue.setFocus( );
addExpressionValue.setText( "" ); //$NON-NLS-1$
}
else
{
addBtn.setEnabled( false );
}
}
} );
new Label( group, SWT.NONE );
int tableStyle = SWT.SINGLE
| SWT.BORDER
| SWT.H_SCROLL
| SWT.V_SCROLL
| SWT.FULL_SELECTION;
table = new Table( group, tableStyle );
data = new GridData( GridData.FILL_BOTH );
data.horizontalSpan = 4;
table.setLayoutData( data );
table.setHeaderVisible( false );
table.setLinesVisible( true );
TableColumn column;
int i;
String[] columNames = new String[]{
Messages.getString( "FilterConditionBuilder.list.item1" ), //$NON-NLS-1$
};
int[] columLength = new int[]{
288
};
for ( i = 0; i < columNames.length; i++ )
{
column = new TableColumn( table, SWT.NONE, i );
column.setText( columNames[i] );
column.setWidth( columLength[i] );
}
table.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
checkEditDelButtonStatus( );
}
} );
table.addKeyListener( new KeyListener( ) {
public void keyPressed( KeyEvent e )
{
if ( e.keyCode == SWT.DEL )
{
delTableValue( );
}
}
public void keyReleased( KeyEvent e )
{
}
} );
table.addMouseListener( new MouseAdapter( ) {
public void mouseDoubleClick( MouseEvent e )
{
editTableValue( );
}
} );
tableViewer = new TableViewer( table );
tableViewer.setUseHashlookup( true );
tableViewer.setColumnProperties( columNames );
tableViewer.setLabelProvider( tableLableProvier );
tableViewer.setContentProvider( tableContentProvider );
Composite rightPart = new Composite( valueListComposite, SWT.NONE );
data = new GridData( GridData.HORIZONTAL_ALIGN_END );
rightPart.setLayoutData( data );
layout = new GridLayout( );
layout.makeColumnsEqualWidth = true;
rightPart.setLayout( layout );
editBtn = new Button( rightPart, SWT.PUSH );
editBtn.setText( Messages.getString( "FilterConditionBuilder.button.edit" ) ); //$NON-NLS-1$
editBtn.setToolTipText( Messages.getString( "FilterConditionBuilder.button.edit.tooltip" ) ); //$NON-NLS-1$
setButtonLayoutData( editBtn );
GridData gd = (GridData) editBtn.getLayoutData( );
gd.grabExcessVerticalSpace = true;
gd.verticalAlignment = SWT.END;
editBtn.setLayoutData( gd );
editBtn.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
editTableValue( );
}
} );
delBtn = new Button( rightPart, SWT.PUSH );
delBtn.setText( Messages.getString( "FilterConditionBuilder.button.delete" ) ); //$NON-NLS-1$
delBtn.setToolTipText( Messages.getString( "FilterConditionBuilder.button.delete.tooltip" ) ); //$NON-NLS-1$
setButtonLayoutData( delBtn );
delBtn.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
delTableValue( );
}
} );
delAllBtn = new Button( rightPart, SWT.PUSH );
delAllBtn.setText( Messages.getString( "FilterConditionBuilder.button.deleteall" ) ); //$NON-NLS-1$
delAllBtn.setToolTipText( Messages.getString( "FilterConditionBuilder.button.deleteall.tooltip" ) ); //$NON-NLS-1$
setButtonLayoutData( delAllBtn );
gd = (GridData) delAllBtn.getLayoutData( );
gd.grabExcessVerticalSpace = true;
gd.verticalAlignment = SWT.BEGINNING;
delAllBtn.setLayoutData( gd );
delAllBtn.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
int count = valueList.size( );
if ( count > 0 )
{
valueList.clear( );
tableViewer.refresh( );
updateButtons( );
}
else
{
delAllBtn.setEnabled( false );
}
}
} );
addExpressionValue.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkAddButtonStatus( );
updateButtons( );
}
} );
// addExpressionValue.addListener( SWT.Verify, expValueVerifyListener );
// addExpressionValue.addListener( SWT.Selection,
// expValueSelectionListener );
refreshList( );
addExpressionValue.setItems( popupItems );
addExpressionValue.addSelectionListener( 0, mAddSelValueAction );
addExpressionValue.addSelectionListener( 1, mAddExpValueAction );
parent.getParent( ).layout( true, true );
if ( getButtonBar( ) != null )
parent.getShell( ).pack( );
return 1;
}
protected ITableLabelProvider tableLableProvier = new ITableLabelProvider( ) {
public Image getColumnImage( Object element, int columnIndex )
{
return null;
}
public String getColumnText( Object element, int columnIndex )
{
if ( columnIndex == 0 )
{
if ( element instanceof Expression )
{
return ( (Expression) element ).getStringExpression( );
}
return element.toString( );
}
return ""; //$NON-NLS-1$
}
public void addListener( ILabelProviderListener listener )
{
}
public void dispose( )
{
}
public boolean isLabelProperty( Object element, String property )
{
return false;
}
public void removeListener( ILabelProviderListener listener )
{
}
};
protected IStructuredContentProvider tableContentProvider = new IStructuredContentProvider( ) {
public void dispose( )
{
}
public void inputChanged( Viewer viewer, Object oldInput,
Object newInput )
{
}
public Object[] getElements( Object inputElement )
{
if ( inputElement == null )
{
return new Object[0];
}
else if ( inputElement instanceof List )
{
return ( (List) inputElement ).toArray( );
}
return null;
}
};
protected void operatorChange( )
{
String value = getValueForOperator( operator.getText( ) );
valueVisible = determineValueVisible( value );
if ( valueVisible == 3 )
{
int ret = createValueListComposite( operator.getParent( ) );
if ( ret != 0 )
{
if ( filterCondition != null )
{
valueList = new ArrayList( filterCondition.getValue1List( ) );
}
tableViewer.setInput( valueList );
}
}
else
{
int ret = create2ValueComposite( operator.getParent( ) );
if ( ret != 0 && filterCondition != null )
{
expressionValue1.setText( DEUtil.resolveNull( filterCondition.getValue1( ) ) );
expressionValue2.setText( DEUtil.resolveNull( filterCondition.getValue2( ) ) );
}
}
if ( valueVisible == 0 )
{
expressionValue1.setVisible( false );
expressionValue2.setVisible( false );
andLable.setVisible( false );
}
else if ( valueVisible == 1 )
{
expressionValue1.setVisible( true );
expressionValue2.setVisible( false );
andLable.setVisible( false );
}
else if ( valueVisible == 2 )
{
expressionValue1.setVisible( true );
expressionValue2.setVisible( true );
andLable.setVisible( true );
andLable.setEnabled( true );
}
updateButtons( );
}
protected SelectionListener operatorSelection = new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
operatorChange( );
}
};
protected Object getResultSetColumn( String name )
{
if ( columnList.isEmpty( ) )
{
return null;
}
for ( int i = 0; i < columnList.size( ); i++ )
{
if ( getColumnName( columnList.get( i ) ).equals( name ) )
{
return columnList.get( i );
}
}
return null;
}
protected Composite createDummy( Composite parent, int colSpan )
{
Composite dummy = new Composite( parent, SWT.NONE );
GridData gdata = new GridData( );
gdata.widthHint = 22;
gdata.horizontalSpan = colSpan;
gdata.heightHint = 10;
dummy.setLayoutData( gdata );
return dummy;
}
/*
* Update handle for the Map Rule builder
*/
public void updateHandle( FilterConditionHandle handle, int handleCount )
{
this.filterCondition = handle;
}
/*
* Set design handle for the Map Rule builder
*/
public void setDesignHandle( DesignElementHandle handle )
{
this.designHandle = handle;
setColumnList( this.designHandle );
}
/*
* If set dataset handle , then the priority of the dataset is first.
*/
public void setDataSetHandle( DataSetHandle handle )
{
this.dataSetHandle = handle;
setColumnList( this.dataSetHandle );
}
public void setDataSetHandle( DataSetHandle handle,
IExpressionProvider provider )
{
setDataSetHandle( handle );
this.expressionProvider = provider;
}
protected IExpressionProvider expressionProvider;
public void setDesignHandle( DesignElementHandle handle,
IExpressionProvider provider )
{
setDesignHandle( handle );
this.expressionProvider = provider;
setColumnList( this.designHandle );
}
private DataSetHandle dataset;
protected void setColumnList( DesignElementHandle handle )
{
if ( handle instanceof DataSetHandle )
{
dataset = (DataSetHandle) handle;
try
{
columnList = DataUtil.getColumnList( dataset );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
else if ( handle instanceof TabularCubeHandle
|| handle instanceof TabularHierarchyHandle )
{
try
{
if ( handle instanceof TabularCubeHandle )
dataset = ( (TabularCubeHandle) handle ).getDataSet( );
else
{
dataset = ( (TabularHierarchyHandle) handle ).getDataSet( );
if ( dataset == null
&& ( (TabularHierarchyHandle) handle ).getLevelCount( ) > 0 )
{
dataset = ( (TabularCubeHandle) ( (TabularHierarchyHandle) handle ).getContainer( )
.getContainer( ) ).getDataSet( );
}
}
if ( dataset != null )
columnList = DataUtil.getColumnList( dataset );
else
columnList = Collections.EMPTY_LIST;
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
else
{
columnList = DEUtil.getVisiableColumnBindingsList( handle );
}
}
/*
* Return the hanle of Map Rule builder
*/
public FilterConditionHandle getInputHandle( )
{
return filterCondition;
}
/**
* Refreshes the OK button state.
*
*/
protected void updateButtons( )
{
enableInput( isExpressionOK( ) );
if ( getButton( IDialogConstants.OK_ID ) != null )
{
getButton( IDialogConstants.OK_ID ).setEnabled( isConditionOK( ) );
}
}
protected void enableInput( boolean val )
{
operator.setEnabled( val );
if ( valueVisible != 3 )
{
if ( expressionValue1 != null )
expressionValue1.setEnabled( val );
if ( expressionValue2 != null )
expressionValue2.setEnabled( val );
if ( andLable != null )
{
andLable.setEnabled( val );
}
}
else
{
setControlEnable( valueListComposite, val );
if ( val )
{
checkAddButtonStatus( );
checkEditDelButtonStatus( );
} // or set all the children control to false
}
}
protected void setControlEnable( Control control, boolean bool )
{
if ( control == null || control.isDisposed( ) )
{
return;
}
control.setEnabled( bool );
Composite tmp = null;
if ( control instanceof Composite )
{
tmp = (Composite) control;
}
if ( tmp != null && tmp.getChildren( ) != null )
{
for ( int i = 0; i < tmp.getChildren( ).length; i++ )
{
setControlEnable( tmp.getChildren( )[i], bool );
}
}
}
/**
* Gets if the expression field is not empty.
*/
protected boolean isExpressionOK( )
{
if ( expression == null )
{
return false;
}
if ( expression.getText( ) == null
|| expression.getText( ).length( ) == 0 )
{
return false;
}
return true;
}
/**
* Gets if the condition is available.
*/
protected boolean isConditionOK( )
{
if ( expression == null )
{
return false;
}
if ( !isExpressionOK( ) )
{
return false;
}
return checkValues( );
}
/**
* Gets if the values of the condition is(are) available.
*/
protected boolean checkValues( )
{
if ( valueVisible == 3 )
{
if ( valueList.size( ) <= 0 )
{
return false;
}
else
{
return true;
}
}
else
{
assert ( !expressionValue1.isDisposed( ) );
assert ( !expressionValue2.isDisposed( ) );
if ( expressionValue1.getVisible( ) )
{
if ( expressionValue1.getText( ) == null
|| expressionValue1.getText( ).trim( ).length( ) == 0 )
{
return false;
}
}
if ( expressionValue2.getVisible( ) )
{
if ( expressionValue2.getText( ) == null
|| expressionValue2.getText( ).trim( ).length( ) == 0 )
{
return false;
}
}
}
return true;
}
protected void checkAddButtonStatus( )
{
if ( addExpressionValue != null )
{
String value = addExpressionValue.getText( );
if ( value == null
|| value.length( ) == 0
|| value.trim( ).length( ) == 0 )
{
addBtn.setEnabled( false );
return;
}
if ( value != null )
{
value = value.trim( );
}
if ( valueList.indexOf( value ) < 0 )
{
addBtn.setEnabled( true );
}
else
{
addBtn.setEnabled( false );
}
}
}
protected void checkEditDelButtonStatus( )
{
if ( tableViewer == null )
{
return;
}
boolean enabled = ( tableViewer.getSelection( ) == null ) ? false
: true;
if ( enabled == true
&& tableViewer.getSelection( ) instanceof StructuredSelection )
{
StructuredSelection selection = (StructuredSelection) tableViewer.getSelection( );
if ( selection.toList( ).size( ) <= 0 )
{
enabled = false;
}
}
editBtn.setEnabled( enabled );
delBtn.setEnabled( enabled );
enabled = table.getItemCount( ) > 0 ? true : false;
delAllBtn.setEnabled( enabled );
}
private void setExpression( )
{
ExpressionButtonUtil.initExpressionButtonControl( expression,
filterCondition,
FilterCondition.EXPR_MEMBER );
}
/**
* SYNC the control value according to the handle.
*/
protected void syncViewProperties( )
{
filterCondition.getProperty( FilterCondition.EXPR_MEMBER );
setExpression( );
operator.select( getIndexForOperatorValue( filterCondition.getOperator( ) ) );
valueVisible = determineValueVisible( filterCondition.getOperator( ) );
if ( valueVisible == 3 )
{
createValueListComposite( operator.getParent( ) );
valueList = new ArrayList( filterCondition.getValue1List( ) );
tableViewer.setInput( valueList );
}
else
{
create2ValueComposite( operator.getParent( ) );
expressionValue1.setText( DEUtil.resolveNull( filterCondition.getValue1( ) ) );
expressionValue2.setText( DEUtil.resolveNull( filterCondition.getValue2( ) ) );
}
if ( valueVisible == 0 )
{
expressionValue1.setVisible( false );
expressionValue2.setVisible( false );
andLable.setVisible( false );
}
else if ( valueVisible == 1 )
{
expressionValue1.setVisible( true );
expressionValue2.setVisible( false );
andLable.setVisible( false );
}
else if ( valueVisible == 2 )
{
expressionValue1.setVisible( true );
expressionValue2.setVisible( true );;
andLable.setVisible( true );
andLable.setEnabled( true );
}
else if ( valueVisible == 3 )
{
if ( expression.getText( ).length( ) == 0 )
{
valueListComposite.setEnabled( false );
}
else
{
valueListComposite.setEnabled( true );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
protected void okPressed( )
{
try
{
if ( filterCondition == null )
{
FilterCondition filter = StructureFactory.createFilterCond( );
filter.setProperty( FilterCondition.OPERATOR_MEMBER,
DEUtil.resolveNull( getValueForOperator( operator.getText( ) ) ) );
if ( valueVisible == 3 )
{
filter.setValue1( valueList );
filter.setValue2( "" ); //$NON-NLS-1$
}
else
{
assert ( !expressionValue1.isDisposed( ) );
assert ( !expressionValue2.isDisposed( ) );
if ( expressionValue1.getVisible( ) )
{
filter.setValue1( DEUtil.resolveNull( expressionValue1.getText( ) ) );
}
else
{
filter.setValue1( NULL_STRING );
}
if ( expressionValue2.getVisible( ) )
{
filter.setValue2( DEUtil.resolveNull( expressionValue2.getText( ) ) );
}
}
// set test expression for new map rule
ExpressionButtonUtil.saveExpressionButtonControl( expression,
filter,
FilterCondition.EXPR_MEMBER );
if ( dataSetHandle != null )
{
PropertyHandle propertyHandle = dataSetHandle.getPropertyHandle( ListingHandle.FILTER_PROP );
propertyHandle.addItem( filter );
}
else
{
PropertyHandle propertyHandle = designHandle.getPropertyHandle( ListingHandle.FILTER_PROP );
propertyHandle.addItem( filter );
}
}
else
{
filterCondition.setOperator( DEUtil.resolveNull( getValueForOperator( operator.getText( ) ) ) );
if ( valueVisible == 3 )
{
filterCondition.setValue1( valueList );
filterCondition.setValue2( NULL_STRING );
}
else
{
assert ( !expressionValue1.isDisposed( ) );
assert ( !expressionValue2.isDisposed( ) );
if ( expressionValue1.getVisible( ) )
{
filterCondition.setValue1( DEUtil.resolveNull( expressionValue1.getText( ) ) );
}
else
{
filterCondition.setValue1( NULL_STRING );
}
if ( expressionValue2.getVisible( ) )
{
filterCondition.setValue2( DEUtil.resolveNull( expressionValue2.getText( ) ) );
}
else
{
filterCondition.setValue2( NULL_STRING );
}
}
ExpressionButtonUtil.saveExpressionButtonControl( expression,
filterCondition,
FilterCondition.EXPR_MEMBER );
}
}
catch ( Exception e )
{
ExceptionUtil.handle( e );
}
super.okPressed( );
}
protected void editValue( Control control )
{
String initValue = null;
if ( control instanceof Text )
{
initValue = ( (Text) control ).getText( );
}
else if ( control instanceof Combo )
{
initValue = ( (Combo) control ).getText( );
}
ExpressionBuilder expressionBuilder = new ExpressionBuilder( getShell( ),
initValue );
setProviderForExpressionBuilder( expressionBuilder );
if ( expressionBuilder.open( ) == OK )
{
String result = DEUtil.resolveNull( expressionBuilder.getResult( ) );
if ( control instanceof Text )
{
( (Text) control ).setText( result );
}
else if ( control instanceof Combo )
{
( (Combo) control ).setText( result );
}
}
updateButtons( );
}
private void setProviderForExpressionBuilder(
ExpressionBuilder expressionBuilder )
{
if ( dataSetHandle != null )
{
if ( expressionProvider == null )
{
expressionBuilder.setExpressionProvier( new ExpressionProvider( dataSetHandle ) );
}
else
{
expressionBuilder.setExpressionProvier( expressionProvider );
}
}
else if ( designHandle != null )
{
if ( expressionProvider == null )
{
if ( designHandle instanceof TabularCubeHandle
|| designHandle instanceof TabularHierarchyHandle )
{
expressionBuilder.setExpressionProvier( new BindingExpressionProvider( designHandle,
null ) );
}
else
{
expressionBuilder.setExpressionProvier( new ExpressionProvider( designHandle ) );
}
}
else
{
expressionBuilder.setExpressionProvier( expressionProvider );
}
}
}
/**
* Sets the model input.
*
* @param sortKey
*/
public void setInput( Object inputHandle )
{
if ( inputHandle instanceof FilterConditionHandle )
{
this.filterCondition = (FilterConditionHandle) inputHandle;
}
else
{
this.filterCondition = null;
}
}
private void refreshList( )
{
if ( refreshItems )
{
ArrayList finalItems = new ArrayList( 10 );
for ( int n = 0; n < actions.length; n++ )
{
finalItems.add( actions[n] );
}
if ( currentItem != null )
{
// addParamterItems( finalItems );
}
popupItems = (String[]) finalItems.toArray( EMPTY_ARRAY );
}
refreshItems = false;
}
private List getSelectValueList( ) throws BirtException
{
List selectValueList = new ArrayList( );
ReportItemHandle reportItem = DEUtil.getBindingHolder( currentItem );
if ( bindingName != null && reportItem != null )
{
selectValueList = SelectValueFetcher.getSelectValueList( expression.getText( ),
reportItem.getDataSet( ),
false );
}
else
{
ExceptionHandler.openErrorMessageBox( Messages.getString( "SelectValueDialog.errorRetrievinglist" ), Messages.getString( "SelectValueDialog.noExpressionSet" ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
return selectValueList;
}
public int open( )
{
if ( getShell( ) == null )
{
// create the window
create( );
}
updateButtons( );
return super.open( );
}
protected ValueCombo.ISelection selectValueAction = new ValueCombo.ISelection( ) {
public String doSelection( String input )
{
String retValue = null;
if ( dataSetHandle != null
|| designHandle instanceof TabularCubeHandle
|| designHandle instanceof TabularHierarchyHandle )
{
DataSetHandle dataSet = null;
if ( dataSetHandle != null )
{
dataSet = dataSetHandle;
}
else
{
if ( designHandle instanceof TabularCubeHandle )
{
dataSet = ( (TabularCubeHandle) designHandle ).getDataSet( );
}
else
{
dataSet = ( (TabularHierarchyHandle) designHandle ).getDataSet( );
}
}
String expressionString = expression.getText( );
try
{
List selectValueList = SelectValueFetcher.getSelectValueList( expressionString,
dataSet );
SelectValueDialog dialog = new SelectValueDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
dialog.setSelectedValueList( selectValueList );
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
retValue = dialog.getSelectedExprValue( );
}
}
catch ( BirtException e1 )
{
MessageDialog.openError( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
+ "\n" //$NON-NLS-1$
+ e1.getMessage( ) );
}
}
else
{
for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); )
{
String columnName = getColumnName( iter.next( ) );
if ( DEUtil.getColumnExpression( columnName )
.equals( expression.getText( ) ) )
{
bindingName = columnName;
break;
}
}
if ( bindingName != null )
{
try
{
List selectValueList = getSelectValueList( );
SelectValueDialog dialog = new SelectValueDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
dialog.setSelectedValueList( selectValueList );
if ( bindingParams != null )
{
dialog.setBindingParams( bindingParams );
}
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
retValue = dialog.getSelectedExprValue( );
}
}
catch ( Exception ex )
{
MessageDialog.openError( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
+ "\n" //$NON-NLS-1$
+ ex.getMessage( ) );
}
}
else
{
MessageDialog.openInformation( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.info.selectVauleUnavailable" ) ); //$NON-NLS-1$
}
}
return retValue;
}
};
protected ValueCombo.ISelection expValueAction = new ValueCombo.ISelection( ) {
public String doSelection( String input )
{
String retValue = null;
ExpressionBuilder dialog = new ExpressionBuilder( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
input );
if ( expressionProvider == null )
dialog.setExpressionProvider( new ExpressionProvider( designHandle ) );
else
dialog.setExpressionProvider( expressionProvider );
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
retValue = dialog.getResult( );
}
return retValue;
}
};
protected MultiValueCombo.ISelection mAddExpValueAction = new MultiValueCombo.ISelection( ) {
public String[] doSelection( String input )
{
String[] retValue = null;
ExpressionBuilder dialog = new ExpressionBuilder( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
input );
if ( expressionProvider == null )
dialog.setExpressionProvider( new ExpressionProvider( designHandle ) );
else
dialog.setExpressionProvider( expressionProvider );
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
if ( dialog.getResult( ).length( ) != 0 )
{
retValue = new String[]{
dialog.getResult( )
};
}
}
return retValue;
}
public void doAfterSelection( MultiValueCombo combo )
{
mAddSelValueAction.doAfterSelection( combo );
}
};
protected MultiValueCombo.ISelection mAddSelValueAction = new MultiValueCombo.ISelection( ) {
public String[] doSelection( String input )
{
String[] retValue = null;
if ( dataSetHandle != null
|| designHandle instanceof TabularCubeHandle
|| designHandle instanceof TabularHierarchyHandle )
{
DataSetHandle dataSet;
if ( dataSetHandle != null )
{
dataSet = dataSetHandle;
}
else
{
if ( designHandle instanceof TabularCubeHandle )
dataSet = ( (TabularCubeHandle) designHandle ).getDataSet( );
else
{
dataSet = ( (TabularHierarchyHandle) designHandle ).getDataSet( );
if ( dataSet == null
&& ( (TabularHierarchyHandle) designHandle ).getLevelCount( ) > 0 )
{
dataSet = ( (TabularCubeHandle) ( (TabularHierarchyHandle) designHandle ).getContainer( )
.getContainer( ) ).getDataSet( );
}
}
}
String expressionString = expression.getText( );
try
{
List selectValueList = SelectValueFetcher.getSelectValueList( expressionString,
dataSet );
SelectValueDialog dialog = new SelectValueDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
dialog.setSelectedValueList( selectValueList );
dialog.setMultipleSelection( true );
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
retValue = dialog.getSelectedExprValues( );
}
}
catch ( BirtException e1 )
{
MessageDialog.openError( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
+ "\n" //$NON-NLS-1$
+ e1.getMessage( ) );
}
}
else
{
for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); )
{
Object obj = iter.next( );
String columnName = Messages.getString( "ExpressionValueCellEditor.title" ); //$NON-NLS-1$
if ( obj instanceof ComputedColumnHandle )
{
columnName = ( (ComputedColumnHandle) ( obj ) ).getName( );
}
else if ( obj instanceof ResultSetColumnHandle )
{
columnName = ( (ResultSetColumnHandle) ( obj ) ).getColumnName( );
}
if ( DEUtil.getColumnExpression( columnName )
.equals( expression.getText( ) ) )
{
bindingName = columnName;
break;
}
}
if ( bindingName != null )
{
try
{
List selectValueList = getSelectValueList( );
SelectValueDialog dialog = new SelectValueDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
Messages.getString( "ExpressionValueCellEditor.title" ) ); //$NON-NLS-1$
dialog.setMultipleSelection( true );
dialog.setSelectedValueList( selectValueList );
if ( bindingParams != null )
{
dialog.setBindingParams( bindingParams );
}
if ( dialog.open( ) == IDialogConstants.OK_ID )
{
retValue = dialog.getSelectedExprValues( );
}
}
catch ( Exception ex )
{
MessageDialog.openError( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.error.selectVauleUnavailable" ) //$NON-NLS-1$
+ "\n" //$NON-NLS-1$
+ ex.getMessage( ) );
}
}
else
{
MessageDialog.openInformation( null,
Messages.getString( "SelectValueDialog.selectValue" ), //$NON-NLS-1$
Messages.getString( "SelectValueDialog.messages.info.selectVauleUnavailable" ) ); //$NON-NLS-1$
}
}
return retValue;
}
public void doAfterSelection( MultiValueCombo combo )
{
addBtn.setEnabled( false );
if ( addExpressionValue.getSelStrings( ).length == 1 )
{
addExpressionValue.setText( DEUtil.resolveNull( addExpressionValue.getSelStrings( )[0] ) );
}
else if ( addExpressionValue.getSelStrings( ).length > 1 )
{
addExpressionValue.setText( "" ); //$NON-NLS-1$
}
boolean change = false;
for ( int i = 0; i < addExpressionValue.getSelStrings( ).length; i++ )
{
if ( valueList.indexOf( DEUtil.resolveNull( addExpressionValue.getSelStrings( )[i] ) ) < 0 )
{
valueList.add( DEUtil.resolveNull( addExpressionValue.getSelStrings( )[i] ) );
change = true;
}
}
if ( change )
{
tableViewer.refresh( );
updateButtons( );
addExpressionValue.setFocus( );
}
}
};
protected void editTableValue( )
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection( );
if ( selection.getFirstElement( ) != null
&& selection.getFirstElement( ) instanceof String )
{
String initValue = (String) selection.getFirstElement( );
ExpressionBuilder expressionBuilder = new ExpressionBuilder( getShell( ),
initValue );
if ( designHandle != null )
{
if ( expressionProvider == null )
{
if ( designHandle instanceof TabularCubeHandle
|| designHandle instanceof TabularHierarchyHandle )
{
expressionBuilder.setExpressionProvider( new BindingExpressionProvider( designHandle,
null ) );
}
else
{
expressionBuilder.setExpressionProvider( new ExpressionProvider( designHandle ) );
}
}
else
{
expressionBuilder.setExpressionProvider( expressionProvider );
}
}
if ( expressionBuilder.open( ) == OK )
{
String result = DEUtil.resolveNull( expressionBuilder.getResult( ) );
if ( result.length( ) == 0 )
{
MessageDialog.openInformation( getShell( ),
Messages.getString( "MapRuleBuilderDialog.MsgDlg.Title" ), //$NON-NLS-1$
Messages.getString( "MapRuleBuilderDialog.MsgDlg.Msg" ) ); //$NON-NLS-1$
return;
}
int index = table.getSelectionIndex( );
valueList.remove( index );
valueList.add( index, result );
tableViewer.refresh( );
table.select( index );
}
updateButtons( );
}
else
{
editBtn.setEnabled( false );
}
}
protected void delTableValue( )
{
int index = table.getSelectionIndex( );
if ( index > -1 )
{
valueList.remove( index );
tableViewer.refresh( );
if ( valueList.size( ) > 0 )
{
if ( valueList.size( ) <= index )
{
index = index - 1;
}
table.select( index );
}
updateButtons( );
}
else
{
delBtn.setEnabled( false );
}
}
} | - Summary: Cannot dataset select columns from expression builder when add filter[0802]
- Bugzilla Bug (s) Resolved: 287534
- Description: Fixed the incorrect parameters which are passed to the ExpressionButtonUtil
- Tests Description: Manual test.
- Notes to Build Team:
- Notes to Developers:
- Notes to QA:
- Notes to Documentation:
- Files Added:
- Files Edited:
- Files Deleted:
| UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/dialogs/FilterConditionBuilder.java | - Summary: Cannot dataset select columns from expression builder when add filter[0802] | <ide><path>I/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/dialogs/FilterConditionBuilder.java
<ide> ExpressionButtonUtil.createExpressionButton( condition,
<ide> expression,
<ide> getExpressionProvider( ),
<del> designHandle,
<add> dataSetHandle != null ? dataSetHandle : designHandle,
<ide> listener );
<ide>
<ide> operator = new Combo( condition, SWT.READ_ONLY ); |
|
JavaScript | mit | 3ee1c040cbe815eaa79b625aa5bcbc926471fa75 | 0 | mingaldrichgan/gatsby,0x80/gatsby,ChristopherBiscardi/gatsby,0x80/gatsby,ChristopherBiscardi/gatsby,gatsbyjs/gatsby,gatsbyjs/gatsby,gatsbyjs/gatsby,ChristopherBiscardi/gatsby,0x80/gatsby,gatsbyjs/gatsby,gatsbyjs/gatsby,mingaldrichgan/gatsby,ChristopherBiscardi/gatsby,gatsbyjs/gatsby,fk/gatsby,mingaldrichgan/gatsby,fk/gatsby,fk/gatsby | // @flow
import Joi from "joi"
import chalk from "chalk"
const _ = require(`lodash`)
const { bindActionCreators } = require(`redux`)
const { stripIndent } = require(`common-tags`)
const glob = require(`glob`)
const path = require(`path`)
const fs = require(`fs`)
const { joinPath } = require(`../utils/path`)
const {
getNode,
hasNodeChanged,
trackSubObjectsToRootNodeId,
} = require(`./index`)
const { store } = require(`./index`)
import * as joiSchemas from "../joi-schemas/joi"
import { generateComponentChunkName } from "../utils/js-chunk-names"
const actions = {}
type Job = {
id: string,
}
type PageInput = {
path: string,
component: string,
layout?: string,
context?: Object,
}
type LayoutInput = {
id?: string,
machineId?: string,
component: string,
layout?: string,
context?: Object,
}
type Page = {
path: string,
matchPath: ?string,
component: string,
context: Object,
internalComponentName: string,
jsonName: string,
componentChunkName: string,
layout: ?string,
updatedAt: number,
}
type Layout = {
id: any,
context: Object,
component: string,
componentWrapperPath: string,
componentChunkName: string,
internalComponentName: string,
jsonName: string,
isLayout: true,
}
type Plugin = {
name: string,
}
/**
* Delete a page
* @param {Object} page a page object with at least the path set
* @param {string} page.path The path of the page
* @param {string} page.component The absolute path to the page component
* @example
* deletePage(page)
*/
actions.deletePage = (page: PageInput) => {
return {
type: `DELETE_PAGE`,
payload: page,
}
}
const pascalCase = _.flow(_.camelCase, _.upperFirst)
/**
* Create a page. See [the guide on creating and modifying pages](/docs/creating-and-modifying-pages/)
* for detailed documenation about creating pages.
* @param {Object} page a page object
* @param {string} page.path Any valid URL. Must start with a forward slash
* @param {string} page.component The absolute path to the component for this page
* @param {string} page.layout The name of the layout for this page. By default
* `'index'` layout is used
* @param {Object} page.context Context data for this page. Passed as props
* to the component `this.props.pathContext` as well as to the graphql query
* as graphql arguments.
* @example
* createPage({
* path: `/my-sweet-new-page/`,
* component: path.resolve(`./src/templates/my-sweet-new-page.js`),
* // If you have a layout component at src/layouts/blog-layout.js
* layout: `blog-layout`,
* // The context is passed as props to the component as well
* // as into the component's GraphQL query.
* context: {
* id: `123456`,
* },
* })
*/
actions.createPage = (page: PageInput, plugin?: Plugin, traceId?: string) => {
let noPageOrComponent = false
let name = `The plugin "${plugin.name}"`
if (plugin.name === `default-site-plugin`) {
name = `Your site's "gatsby-node.js"`
}
if (!page.path) {
const message = `${name} must set the page path when creating a page`
// Don't log out when testing
if (process.env.NODE_ENV !== `test`) {
console.log(chalk.bold.red(message))
console.log(``)
console.log(page)
} else {
return message
}
noPageOrComponent = true
}
if (!page.component || !path.isAbsolute(page.component)) {
const message = `${name} must set the absolute path to the page component when create creating a page`
// Don't log out when testing
if (process.env.NODE_ENV !== `test`) {
console.log(chalk.bold.red(message))
console.log(``)
console.log(page)
} else {
return message
}
noPageOrComponent = true
}
if (noPageOrComponent) {
console.log(``)
console.log(
`See the documentation for createPage https://www.gatsbyjs.org/docs/bound-action-creators/#createPage`
)
process.exit(1)
}
let jsonName = `${_.kebabCase(page.path)}.json`
let internalComponentName = `Component${pascalCase(page.path)}`
if (jsonName === `.json`) {
jsonName = `index.json`
internalComponentName = `ComponentIndex`
}
let layout = page.layout || null
// If no layout is set we try fallback to `/src/layouts/index`.
if (
!layout &&
glob.sync(
joinPath(store.getState().program.directory, `src/layouts/index.*`)
).length
) {
layout = `index`
}
let internalPage: Page = {
layout,
jsonName,
internalComponentName,
path: page.path,
matchPath: page.matchPath,
component: page.component,
componentChunkName: generateComponentChunkName(page.component),
// Ensure the page has a context object
context: page.context || {},
updatedAt: Date.now(),
}
// If the path doesn't have an initial forward slash, add it.
if (internalPage.path[0] !== `/`) {
internalPage.path = `/${internalPage.path}`
}
const result = Joi.validate(internalPage, joiSchemas.pageSchema)
if (result.error) {
console.log(chalk.blue.bgYellow(`The upserted page didn't pass validation`))
console.log(chalk.bold.red(result.error))
console.log(internalPage)
return null
}
// Validate that the page component imports React and exports something
// (hopefully a component).
if (!internalPage.component.includes(`/.cache/`)) {
const fileContent = fs.readFileSync(internalPage.component, `utf-8`)
let notEmpty = true
let includesReactImport = true
let includesDefaultExport = true
if (fileContent === ``) {
notEmpty = false
}
if (!fileContent.includes(`React`)) {
includesReactImport = false
}
if (
!fileContent.includes(`export default`) &&
!fileContent.includes(`module.exports`) &&
!fileContent.includes(`exports.default`)
) {
includesDefaultExport = false
}
if (!notEmpty || !includesDefaultExport || !includesReactImport) {
const relativePath = path.relative(
store.getState().program.directory,
internalPage.component
)
if (!notEmpty) {
console.log(``)
console.log(
`You have an empty file in the "src/pages" directory at "${relativePath}". Please remove it or make it a valid component`
)
console.log(``)
process.exit(1)
}
console.log(``)
console.log(``)
console.log(
`The page component at "${relativePath}" didn't pass validation`
)
if (!includesReactImport) {
console.log(``)
console.log(
`You must import React at the top of the file for a React component to be valid`
)
console.log(``)
console.log(`Add the following to the top of the component:`)
console.log(``)
console.log(` import React from 'react'`)
console.log(``)
}
if (!includesDefaultExport) {
console.log(``)
console.log(
`The page component must export a React component for it to be valid`
)
console.log(``)
}
process.exit(1)
}
}
return {
type: `CREATE_PAGE`,
plugin,
traceId,
payload: internalPage,
}
}
/**
* Delete a layout
* @param {string} layout a layout object with at least the name set
* @example
* deleteLayout(layout)
*/
actions.deleteLayout = (layout: Layout, plugin?: Plugin) => {
return {
type: `DELETE_LAYOUT`,
payload: layout,
}
}
/**
* Create a layout. Generally layouts are created automatically by placing a
* React component in the `src/layouts/` directory. This action should be used
* if loading layouts from an NPM package or from a non-standard location.
* @param {Object} layout a layout object
* @param {string} layout.component The absolute path to the component for this layout
* @example
* createLayout({
* component: path.resolve(`./src/templates/myNewLayout.js`),
* id: 'custom-id', // If no id is provided, the filename will be used as id.
* context: {
* title: `My New Layout`
* }
* })
*/
actions.createLayout = (
layout: LayoutInput,
plugin?: Plugin,
traceId?: string
) => {
let id = layout.id || path.parse(layout.component).name
// Add a "machine" id as a universal ID to differentiate layout from
// page components.
const machineId = `layout---${id}`
let componentWrapperPath = joinPath(
store.getState().program.directory,
`.cache`,
`layouts`,
`${id}.js`
)
let internalLayout: Layout = {
id,
machineId,
componentWrapperPath,
isLayout: true,
jsonName: `layout-${_.kebabCase(id)}.json`,
internalComponentName: `Component-layout-${pascalCase(id)}`,
component: layout.component,
componentChunkName: generateComponentChunkName(layout.component),
// Ensure the page has a context object
context: layout.context || {},
}
const result = Joi.validate(internalLayout, joiSchemas.layoutSchema)
if (result.error) {
console.log(
chalk.blue.bgYellow(`The upserted layout didn't pass validation`)
)
console.log(chalk.bold.red(result.error))
console.log(internalLayout)
return null
}
return {
type: `CREATE_LAYOUT`,
plugin,
traceId,
payload: internalLayout,
}
}
/**
* Delete a node
* @param {string} nodeId a node id
* @param {object} node the node object
* @example
* deleteNode(node.id, node)
*/
actions.deleteNode = (nodeId: string, node: any, plugin: Plugin) => {
return {
type: `DELETE_NODE`,
plugin,
node,
payload: nodeId,
}
}
/**
* Batch delete nodes
* @param {Array} nodes an array of node ids
* @example
* deleteNodes([`node1`, `node2`])
*/
actions.deleteNodes = (nodes: any[], plugin: Plugin) => {
return {
type: `DELETE_NODES`,
plugin,
payload: nodes,
}
}
const typeOwners = {}
/**
* Create a new node.
* @param {Object} node a node object
* @param {string} node.id The node's ID. Must be globally unique.
* @param {string} node.parent The ID of the parent's node. If the node is
* derived from another node, set that node as the parent. Otherwise it can
* just be an empty string.
* @param {Array} node.children An array of children node IDs. If you're
* creating the children nodes while creating the parent node, add the
* children node IDs here directly. If you're adding a child node to a
* parent node created by a plugin, you can't mutate this value directly
* to add your node id, instead use the action creator `createParentChildLink`.
* @param {Object} node.internal node fields that aren't generally
* interesting to consumers of node data but are very useful for plugin writers
* and Gatsby core.
* @param {string} node.internal.mediaType An optional field to indicate to
* transformer plugins that your node has raw content they can transform.
* Use either an official media type (we use mime-db as our source
* (https://www.npmjs.com/package/mime-db) or a made-up one if your data
* doesn't fit in any existing bucket. Transformer plugins use node media types
* for deciding if they should transform a node into a new one. E.g.
* markdown transformers look for media types of
* `text/markdown`.
* @param {string} node.internal.type An arbitrary globally unique type
* choosen by the plugin creating the node. Should be descriptive of the
* node as the type is used in forming GraphQL types so users will query
* for nodes based on the type choosen here. Nodes of a given type can
* only be created by one plugin.
* @param {string} node.internal.content An optional field. The raw content
* of the node. Can be excluded if it'd require a lot of memory to load in
* which case you must define a `loadNodeContent` function for this node.
* @param {string} node.internal.contentDigest the digest for the content
* of this node. Helps Gatsby avoid doing extra work on data that hasn't
* changed.
* @example
* createNode({
* // Data for the node.
* field1: `a string`,
* field2: 10,
* field3: true,
* ...arbitraryOtherData,
*
* // Required fields.
* id: `a-node-id`,
* parent: `the-id-of-the-parent-node`, // or null if it's a source node without a parent
* children: [],
* internal: {
* type: `CoolServiceMarkdownField`,
* contentDigest: crypto
* .createHash(`md5`)
* .update(JSON.stringify(fieldData))
* .digest(`hex`),
* mediaType: `text/markdown`, // optional
* content: JSON.stringify(fieldData), // optional
* }
* })
*/
actions.createNode = (node: any, plugin?: Plugin, traceId?: string) => {
if (!_.isObject(node)) {
return console.log(
chalk.bold.red(
`The node passed to the "createNode" action creator must be an object`
)
)
}
// Ensure the new node has an internals object.
if (!node.internal) {
node.internal = {}
}
// Tell user not to set the owner name themself.
if (node.internal.owner) {
console.log(JSON.stringify(node, null, 4))
console.log(
chalk.bold.red(
`The node internal.owner field is set automatically by Gatsby and not by plugin`
)
)
process.exit(1)
}
// Add the plugin name to the internal object.
if (plugin) {
node.internal.owner = plugin.name
}
const result = Joi.validate(node, joiSchemas.nodeSchema)
if (result.error) {
console.log(chalk.bold.red(`The new node didn't pass validation`))
console.log(chalk.bold.red(result.error))
console.log(node)
return { type: `VALIDATION_ERROR`, error: true }
}
// Ensure node isn't directly setting fields.
if (node.fields) {
throw new Error(
stripIndent`
Plugins creating nodes can not set data on the reserved field "fields"
as this is reserved for plugins which wish to extend your nodes.
If your plugin didn't add "fields" you're probably seeing this
error because you're reusing an old node object.
Node:
${JSON.stringify(node, null, 4)}
Plugin that created the node:
${JSON.stringify(plugin, null, 4)}
`
)
}
trackSubObjectsToRootNodeId(node)
const oldNode = getNode(node.id)
// Ensure the plugin isn't creating a node type owned by another
// plugin. Type "ownership" is first come first served.
if (plugin) {
let pluginName = plugin.name
if (!typeOwners[node.internal.type])
typeOwners[node.internal.type] = pluginName
else if (typeOwners[node.internal.type] !== pluginName)
throw new Error(stripIndent`
The plugin "${pluginName}" created a node of a type owned by another plugin.
The node type "${node.internal.type}" is owned by "${
typeOwners[node.internal.type]
}".
If you copy and pasted code from elsewhere, you'll need to pick a new type name
for your new node(s).
The node object passed to "createNode":
${JSON.stringify(node, null, 4)}
The plugin creating the node:
${JSON.stringify(plugin, null, 4)}
`)
// If the node has been created in the past, check that
// the current plugin is the same as the previous.
if (oldNode && oldNode.internal.owner !== pluginName) {
throw new Error(
stripIndent`
Nodes can only be updated by their owner. Node "${node.id}" is
owned by "${oldNode.internal.owner}" and another plugin "${pluginName}"
tried to update it.
`
)
}
}
// Check if the node has already been processed.
if (oldNode && !hasNodeChanged(node.id, node.internal.contentDigest)) {
return {
type: `TOUCH_NODE`,
plugin,
traceId,
payload: node.id,
}
} else {
return {
type: `CREATE_NODE`,
plugin,
traceId,
payload: node,
}
}
}
/**
* "Touch" a node. Tells Gatsby a node still exists and shouldn't
* be garbage collected. Primarily useful for source plugins fetching
* nodes from a remote system that can return only nodes that have
* updated. The source plugin then touches all the nodes that haven't
* updated but still exist so Gatsby knows to keep them.
* @param {string} nodeId The id of a node.
* @example
* touchNode(`a-node-id`)
*/
actions.touchNode = (nodeId: string, plugin?: Plugin) => {
return {
type: `TOUCH_NODE`,
plugin,
payload: nodeId,
}
}
type CreateNodeInput = {
node: Object,
fieldName?: string,
fieldValue?: string,
name?: string,
value: any,
}
/**
* Extend another node. The new node field is placed under the `fields`
* key on the extended node object.
*
* Once a plugin has claimed a field name the field name can't be used by
* other plugins. Also since nodes are immutable, you can't mutate the node
* directly. So to extend another node, use this.
* @param {Object} $0
* @param {Object} $0.node the target node object
* @param {string} $0.fieldName [deprecated] the name for the field
* @param {string} $0.fieldValue [deprecated] the value for the field
* @param {string} $0.name the name for the field
* @param {string} $0.value the value for the field
* @example
* createNodeField({
* node,
* name: `happiness`,
* value: `is sweet graphql queries`
* })
*
* // The field value is now accessible at node.fields.happiness
*/
actions.createNodeField = (
{ node, name, value, fieldName, fieldValue }: CreateNodeInput,
plugin: Plugin,
traceId?: string
) => {
if (fieldName) {
console.warn(
`Calling "createNodeField" with "fieldName" is deprecated. Use "name" instead`
)
if (!name) {
name = fieldName
}
}
if (fieldValue) {
console.warn(
`Calling "createNodeField" with "fieldValue" is deprecated. Use "value" instead`
)
if (!value) {
value = fieldValue
}
}
// Ensure required fields are set.
if (!node.internal.fieldOwners) {
node.internal.fieldOwners = {}
}
if (!node.fields) {
node.fields = {}
}
// Check that this field isn't owned by another plugin.
const fieldOwner = node.internal.fieldOwners[name]
if (fieldOwner && fieldOwner !== plugin.name) {
throw new Error(
stripIndent`
A plugin tried to update a node field that it doesn't own:
Node id: ${node.id}
Plugin: ${plugin.name}
name: ${name}
value: ${value}
`
)
}
// Update node
node.fields[name] = value
node.internal.fieldOwners[name] = plugin.name
return {
type: `ADD_FIELD_TO_NODE`,
plugin,
traceId,
payload: node,
}
}
/**
* Creates a link between a parent and child node. This is used when you
* transform content from a node creating a new child node. You need to add
* this new child node to the `children` array of the parent but since you
* don't have direct access to the immutable parent node, use this action
* instead.
* @param {Object} $0
* @param {Object} $0.parent the parent node object
* @param {Object} $0.child the child node object
* @example
* createParentChildLink({ parent: parentNode, child: childNode })
*/
actions.createParentChildLink = (
{ parent, child }: { parent: any, child: any },
plugin?: Plugin
) => {
// Update parent
parent.children.push(child.id)
parent.children = _.uniq(parent.children)
return {
type: `ADD_CHILD_NODE_TO_PARENT_NODE`,
plugin,
payload: parent,
}
}
/**
* Create a dependency between a page and data. Probably for
* internal use only.
* @param {Object} $0
* @param {string} $0.path the path to the page
* @param {string} $0.nodeId A node ID
* @param {string} $0.connection A connection type
* @private
*/
actions.createPageDependency = (
{
path,
nodeId,
connection,
}: { path: string, nodeId: string, connection: string },
plugin: string = ``
) => {
return {
type: `CREATE_COMPONENT_DEPENDENCY`,
plugin,
payload: {
path,
nodeId,
connection,
},
}
}
/**
* Delete dependencies between an array of pages and data. Probably for
* internal use only. Used when deleting pages.
* @param {Array} paths the paths to delete.
* @private
*/
actions.deleteComponentsDependencies = (paths: string[]) => {
return {
type: `DELETE_COMPONENTS_DEPENDENCIES`,
payload: {
paths,
},
}
}
/**
* When the query watcher extracts a graphq query, it calls
* this to store the query with its component.
* @private
*/
actions.replaceComponentQuery = ({
query,
componentPath,
}: {
query: string,
componentPath: string,
}) => {
return {
type: `REPLACE_COMPONENT_QUERY`,
payload: {
query,
componentPath,
},
}
}
/**
* Create a "job". This is a long-running process that are generally
* started as side-effects to GraphQL queries.
* [`gatsby-plugin-sharp`](/packages/gatsby-plugin-sharp/) uses this for
* example.
*
* Gatsby doesn't finish its bootstrap until all jobs are ended.
* @param {Object} job A job object with at least an id set
* @param {id} job.id The id of the job
* @example
* createJob({ id: `write file id: 123`, fileName: `something.jpeg` })
*/
actions.createJob = (job: Job, plugin?: ?Plugin = null) => {
return {
type: `CREATE_JOB`,
plugin,
payload: job,
}
}
/**
* Set (update) a "job". Sometimes on really long running jobs you want
* to update the job as it continues.
*
* @param {Object} job A job object with at least an id set
* @param {id} job.id The id of the job
* @example
* setJob({ id: `write file id: 123`, progress: 50 })
*/
actions.setJob = (job: Job, plugin?: ?Plugin = null) => {
return {
type: `SET_JOB`,
plugin,
payload: job,
}
}
/**
* End a "job".
*
* Gatsby doesn't finish its bootstrap until all jobs are ended.
* @param {Object} job A job object with at least an id set
* @param {id} job.id The id of the job
* @example
* endJob({ id: `write file id: 123` })
*/
actions.endJob = (job: Job, plugin?: ?Plugin = null) => {
return {
type: `END_JOB`,
plugin,
payload: job,
}
}
/**
* Set plugin status. A plugin can use this to save status keys e.g. the last
* it fetched something. These values are persisted between runs of Gatsby.
*
* @param {Object} status An object with arbitrary values set
* @example
* setPluginStatus({ lastFetched: Date.now() })
*/
actions.setPluginStatus = (
status: { [key: string]: mixed },
plugin: Plugin
) => {
return {
type: `SET_PLUGIN_STATUS`,
plugin,
payload: status,
}
}
/**
* Create a redirect from one page to another. Server redirects don't work out
* of the box. You must have a plugin setup to integrate the redirect data with
* your hosting technology e.g. the [Netlify
* plugin](/packages/gatsby-plugin-netlify/)).
*
* @param {Object} redirect Redirect data
* @param {string} redirect.fromPath Any valid URL. Must start with a forward slash
* @param {string} redirect.isPermanent This is a permanent redirect; defaults to temporary
* @param {string} redirect.toPath URL of a created page (see `createPage`)
* @param {string} redirect.redirectInBrowser Redirects are generally for redirecting legacy URLs to their new configuration. If you can't update your UI for some reason, set `redirectInBrowser` to true and Gatsby will handle redirecting in the client as well.
* @example
* createRedirect({ fromPath: '/old-url', toPath: '/new-url', isPermanent: true })
* createRedirect({ fromPath: '/url', toPath: '/zn-CH/url', Language: 'zn' })
*/
actions.createRedirect = ({
fromPath,
isPermanent = false,
redirectInBrowser = false,
toPath,
...rest
}) => {
let pathPrefix = ``
if (store.getState().program.prefixPaths) {
pathPrefix = store.getState().config.pathPrefix
}
return {
type: `CREATE_REDIRECT`,
payload: {
fromPath: `${pathPrefix}${fromPath}`,
isPermanent,
redirectInBrowser,
toPath: `${pathPrefix}${toPath}`,
...rest,
},
}
}
exports.actions = actions
exports.boundActionCreators = bindActionCreators(actions, store.dispatch)
| packages/gatsby/src/redux/actions.js | // @flow
import Joi from "joi"
import chalk from "chalk"
const _ = require(`lodash`)
const { bindActionCreators } = require(`redux`)
const { stripIndent } = require(`common-tags`)
const glob = require(`glob`)
const path = require(`path`)
const fs = require(`fs`)
const { joinPath } = require(`../utils/path`)
const {
getNode,
hasNodeChanged,
trackSubObjectsToRootNodeId,
} = require(`./index`)
const { store } = require(`./index`)
import * as joiSchemas from "../joi-schemas/joi"
import { generateComponentChunkName } from "../utils/js-chunk-names"
const actions = {}
type Job = {
id: string,
}
type PageInput = {
path: string,
component: string,
layout?: string,
context?: Object,
}
type LayoutInput = {
id?: string,
machineId?: string,
component: string,
layout?: string,
context?: Object,
}
type Page = {
path: string,
matchPath: ?string,
component: string,
context: Object,
internalComponentName: string,
jsonName: string,
componentChunkName: string,
layout: ?string,
updatedAt: number,
}
type Layout = {
id: any,
context: Object,
component: string,
componentWrapperPath: string,
componentChunkName: string,
internalComponentName: string,
jsonName: string,
isLayout: true,
}
type Plugin = {
name: string,
}
/**
* Delete a page
* @param {Object} page a page object with at least the path set
* @param {string} page.path The path of the page
* @param {string} page.component The absolute path to the page component
* @example
* deletePage(page)
*/
actions.deletePage = (page: PageInput) => {
return {
type: `DELETE_PAGE`,
payload: page,
}
}
const pascalCase = _.flow(_.camelCase, _.upperFirst)
/**
* Create a page. See [the guide on creating and modifying pages](/docs/creating-and-modifying-pages/)
* for detailed documenation about creating pages.
* @param {Object} page a page object
* @param {string} page.path Any valid URL. Must start with a forward slash
* @param {string} page.component The absolute path to the component for this page
* @param {string} page.layout The name of the layout for this page. By default
* `'index'` layout is used
* @param {Object} page.context Context data for this page. Passed as props
* to the component `this.props.pathContext` as well as to the graphql query
* as graphql arguments.
* @example
* createPage({
* path: `/my-sweet-new-page/`,
* component: path.resolve(`./src/templates/my-sweet-new-page.js`),
* // If you have a layout component at src/layouts/blog-layout.js
* layout: `blog-layout`,
* // The context is passed as props to the component as well
* // as into the component's GraphQL query.
* context: {
* id: `123456`,
* },
* })
*/
actions.createPage = (page: PageInput, plugin?: Plugin, traceId?: string) => {
let noPageOrComponent = false
let name = `The plugin "${plugin.name}"`
if (plugin.name === `default-site-plugin`) {
name = `Your site's "gatsby-node.js"`
}
if (!page.path) {
const message = `${name} must set the page path when creating a page`
// Don't log out when testing
if (process.env.NODE_ENV !== `test`) {
console.log(chalk.bold.red(message))
console.log(``)
console.log(page)
} else {
return message
}
noPageOrComponent = true
}
if (!page.component || !path.isAbsolute(page.component)) {
const message = `${name} must set the absolute path to the page component when create creating a page`
// Don't log out when testing
if (process.env.NODE_ENV !== `test`) {
console.log(chalk.bold.red(message))
console.log(``)
console.log(page)
} else {
return message
}
noPageOrComponent = true
}
if (noPageOrComponent) {
console.log(``)
console.log(
`See the documentation for createPage https://www.gatsbyjs.org/docs/bound-action-creators/#createPage`
)
process.exit(1)
}
let jsonName = `${_.kebabCase(page.path)}.json`
let internalComponentName = `Component${pascalCase(page.path)}`
if (jsonName === `.json`) {
jsonName = `index.json`
internalComponentName = `ComponentIndex`
}
let layout = page.layout || null
// If no layout is set we try fallback to `/src/layouts/index`.
if (
!layout &&
glob.sync(
joinPath(store.getState().program.directory, `src/layouts/index.*`)
).length
) {
layout = `index`
}
let internalPage: Page = {
layout,
jsonName,
internalComponentName,
path: page.path,
matchPath: page.matchPath,
component: page.component,
componentChunkName: generateComponentChunkName(page.component),
// Ensure the page has a context object
context: page.context || {},
updatedAt: Date.now(),
}
// If the path doesn't have an initial forward slash, add it.
if (internalPage.path[0] !== `/`) {
internalPage.path = `/${internalPage.path}`
}
const result = Joi.validate(internalPage, joiSchemas.pageSchema)
if (result.error) {
console.log(chalk.blue.bgYellow(`The upserted page didn't pass validation`))
console.log(chalk.bold.red(result.error))
console.log(internalPage)
return null
}
// Validate that the page component imports React and exports something
// (hopefully a component).
if (!internalPage.component.includes(`/.cache/`)) {
const fileContent = fs.readFileSync(internalPage.component, `utf-8`)
let notEmpty = true
let includesReactImport = true
let includesDefaultExport = true
if (fileContent === ``) {
notEmpty = false
}
if (!fileContent.includes(`React`)) {
includesReactImport = false
}
if (
!fileContent.includes(`export default`) &&
!fileContent.includes(`module.exports`)
) {
includesDefaultExport = false
}
if (!notEmpty || !includesDefaultExport || !includesReactImport) {
const relativePath = path.relative(
store.getState().program.directory,
internalPage.component
)
if (!notEmpty) {
console.log(``)
console.log(
`You have an empty file in the "src/pages" directory at "${relativePath}". Please remove it or make it a valid component`
)
console.log(``)
process.exit(1)
}
console.log(``)
console.log(``)
console.log(
`The page component at "${relativePath}" didn't pass validation`
)
if (!includesReactImport) {
console.log(``)
console.log(
`You must import React at the top of the file for a React component to be valid`
)
console.log(``)
console.log(`Add the following to the top of the component:`)
console.log(``)
console.log(` import React from 'react'`)
console.log(``)
}
if (!includesDefaultExport) {
console.log(``)
console.log(
`The page component must export a React component for it to be valid`
)
console.log(``)
}
process.exit(1)
}
}
return {
type: `CREATE_PAGE`,
plugin,
traceId,
payload: internalPage,
}
}
/**
* Delete a layout
* @param {string} layout a layout object with at least the name set
* @example
* deleteLayout(layout)
*/
actions.deleteLayout = (layout: Layout, plugin?: Plugin) => {
return {
type: `DELETE_LAYOUT`,
payload: layout,
}
}
/**
* Create a layout. Generally layouts are created automatically by placing a
* React component in the `src/layouts/` directory. This action should be used
* if loading layouts from an NPM package or from a non-standard location.
* @param {Object} layout a layout object
* @param {string} layout.component The absolute path to the component for this layout
* @example
* createLayout({
* component: path.resolve(`./src/templates/myNewLayout.js`),
* id: 'custom-id', // If no id is provided, the filename will be used as id.
* context: {
* title: `My New Layout`
* }
* })
*/
actions.createLayout = (
layout: LayoutInput,
plugin?: Plugin,
traceId?: string
) => {
let id = layout.id || path.parse(layout.component).name
// Add a "machine" id as a universal ID to differentiate layout from
// page components.
const machineId = `layout---${id}`
let componentWrapperPath = joinPath(
store.getState().program.directory,
`.cache`,
`layouts`,
`${id}.js`
)
let internalLayout: Layout = {
id,
machineId,
componentWrapperPath,
isLayout: true,
jsonName: `layout-${_.kebabCase(id)}.json`,
internalComponentName: `Component-layout-${pascalCase(id)}`,
component: layout.component,
componentChunkName: generateComponentChunkName(layout.component),
// Ensure the page has a context object
context: layout.context || {},
}
const result = Joi.validate(internalLayout, joiSchemas.layoutSchema)
if (result.error) {
console.log(
chalk.blue.bgYellow(`The upserted layout didn't pass validation`)
)
console.log(chalk.bold.red(result.error))
console.log(internalLayout)
return null
}
return {
type: `CREATE_LAYOUT`,
plugin,
traceId,
payload: internalLayout,
}
}
/**
* Delete a node
* @param {string} nodeId a node id
* @param {object} node the node object
* @example
* deleteNode(node.id, node)
*/
actions.deleteNode = (nodeId: string, node: any, plugin: Plugin) => {
return {
type: `DELETE_NODE`,
plugin,
node,
payload: nodeId,
}
}
/**
* Batch delete nodes
* @param {Array} nodes an array of node ids
* @example
* deleteNodes([`node1`, `node2`])
*/
actions.deleteNodes = (nodes: any[], plugin: Plugin) => {
return {
type: `DELETE_NODES`,
plugin,
payload: nodes,
}
}
const typeOwners = {}
/**
* Create a new node.
* @param {Object} node a node object
* @param {string} node.id The node's ID. Must be globally unique.
* @param {string} node.parent The ID of the parent's node. If the node is
* derived from another node, set that node as the parent. Otherwise it can
* just be an empty string.
* @param {Array} node.children An array of children node IDs. If you're
* creating the children nodes while creating the parent node, add the
* children node IDs here directly. If you're adding a child node to a
* parent node created by a plugin, you can't mutate this value directly
* to add your node id, instead use the action creator `createParentChildLink`.
* @param {Object} node.internal node fields that aren't generally
* interesting to consumers of node data but are very useful for plugin writers
* and Gatsby core.
* @param {string} node.internal.mediaType An optional field to indicate to
* transformer plugins that your node has raw content they can transform.
* Use either an official media type (we use mime-db as our source
* (https://www.npmjs.com/package/mime-db) or a made-up one if your data
* doesn't fit in any existing bucket. Transformer plugins use node media types
* for deciding if they should transform a node into a new one. E.g.
* markdown transformers look for media types of
* `text/markdown`.
* @param {string} node.internal.type An arbitrary globally unique type
* choosen by the plugin creating the node. Should be descriptive of the
* node as the type is used in forming GraphQL types so users will query
* for nodes based on the type choosen here. Nodes of a given type can
* only be created by one plugin.
* @param {string} node.internal.content An optional field. The raw content
* of the node. Can be excluded if it'd require a lot of memory to load in
* which case you must define a `loadNodeContent` function for this node.
* @param {string} node.internal.contentDigest the digest for the content
* of this node. Helps Gatsby avoid doing extra work on data that hasn't
* changed.
* @example
* createNode({
* // Data for the node.
* field1: `a string`,
* field2: 10,
* field3: true,
* ...arbitraryOtherData,
*
* // Required fields.
* id: `a-node-id`,
* parent: `the-id-of-the-parent-node`, // or null if it's a source node without a parent
* children: [],
* internal: {
* type: `CoolServiceMarkdownField`,
* contentDigest: crypto
* .createHash(`md5`)
* .update(JSON.stringify(fieldData))
* .digest(`hex`),
* mediaType: `text/markdown`, // optional
* content: JSON.stringify(fieldData), // optional
* }
* })
*/
actions.createNode = (node: any, plugin?: Plugin, traceId?: string) => {
if (!_.isObject(node)) {
return console.log(
chalk.bold.red(
`The node passed to the "createNode" action creator must be an object`
)
)
}
// Ensure the new node has an internals object.
if (!node.internal) {
node.internal = {}
}
// Tell user not to set the owner name themself.
if (node.internal.owner) {
console.log(JSON.stringify(node, null, 4))
console.log(
chalk.bold.red(
`The node internal.owner field is set automatically by Gatsby and not by plugin`
)
)
process.exit(1)
}
// Add the plugin name to the internal object.
if (plugin) {
node.internal.owner = plugin.name
}
const result = Joi.validate(node, joiSchemas.nodeSchema)
if (result.error) {
console.log(chalk.bold.red(`The new node didn't pass validation`))
console.log(chalk.bold.red(result.error))
console.log(node)
return { type: `VALIDATION_ERROR`, error: true }
}
// Ensure node isn't directly setting fields.
if (node.fields) {
throw new Error(
stripIndent`
Plugins creating nodes can not set data on the reserved field "fields"
as this is reserved for plugins which wish to extend your nodes.
If your plugin didn't add "fields" you're probably seeing this
error because you're reusing an old node object.
Node:
${JSON.stringify(node, null, 4)}
Plugin that created the node:
${JSON.stringify(plugin, null, 4)}
`
)
}
trackSubObjectsToRootNodeId(node)
const oldNode = getNode(node.id)
// Ensure the plugin isn't creating a node type owned by another
// plugin. Type "ownership" is first come first served.
if (plugin) {
let pluginName = plugin.name
if (!typeOwners[node.internal.type])
typeOwners[node.internal.type] = pluginName
else if (typeOwners[node.internal.type] !== pluginName)
throw new Error(stripIndent`
The plugin "${pluginName}" created a node of a type owned by another plugin.
The node type "${node.internal.type}" is owned by "${
typeOwners[node.internal.type]
}".
If you copy and pasted code from elsewhere, you'll need to pick a new type name
for your new node(s).
The node object passed to "createNode":
${JSON.stringify(node, null, 4)}
The plugin creating the node:
${JSON.stringify(plugin, null, 4)}
`)
// If the node has been created in the past, check that
// the current plugin is the same as the previous.
if (oldNode && oldNode.internal.owner !== pluginName) {
throw new Error(
stripIndent`
Nodes can only be updated by their owner. Node "${node.id}" is
owned by "${oldNode.internal.owner}" and another plugin "${pluginName}"
tried to update it.
`
)
}
}
// Check if the node has already been processed.
if (oldNode && !hasNodeChanged(node.id, node.internal.contentDigest)) {
return {
type: `TOUCH_NODE`,
plugin,
traceId,
payload: node.id,
}
} else {
return {
type: `CREATE_NODE`,
plugin,
traceId,
payload: node,
}
}
}
/**
* "Touch" a node. Tells Gatsby a node still exists and shouldn't
* be garbage collected. Primarily useful for source plugins fetching
* nodes from a remote system that can return only nodes that have
* updated. The source plugin then touches all the nodes that haven't
* updated but still exist so Gatsby knows to keep them.
* @param {string} nodeId The id of a node.
* @example
* touchNode(`a-node-id`)
*/
actions.touchNode = (nodeId: string, plugin?: Plugin) => {
return {
type: `TOUCH_NODE`,
plugin,
payload: nodeId,
}
}
type CreateNodeInput = {
node: Object,
fieldName?: string,
fieldValue?: string,
name?: string,
value: any,
}
/**
* Extend another node. The new node field is placed under the `fields`
* key on the extended node object.
*
* Once a plugin has claimed a field name the field name can't be used by
* other plugins. Also since nodes are immutable, you can't mutate the node
* directly. So to extend another node, use this.
* @param {Object} $0
* @param {Object} $0.node the target node object
* @param {string} $0.fieldName [deprecated] the name for the field
* @param {string} $0.fieldValue [deprecated] the value for the field
* @param {string} $0.name the name for the field
* @param {string} $0.value the value for the field
* @example
* createNodeField({
* node,
* name: `happiness`,
* value: `is sweet graphql queries`
* })
*
* // The field value is now accessible at node.fields.happiness
*/
actions.createNodeField = (
{ node, name, value, fieldName, fieldValue }: CreateNodeInput,
plugin: Plugin,
traceId?: string
) => {
if (fieldName) {
console.warn(
`Calling "createNodeField" with "fieldName" is deprecated. Use "name" instead`
)
if (!name) {
name = fieldName
}
}
if (fieldValue) {
console.warn(
`Calling "createNodeField" with "fieldValue" is deprecated. Use "value" instead`
)
if (!value) {
value = fieldValue
}
}
// Ensure required fields are set.
if (!node.internal.fieldOwners) {
node.internal.fieldOwners = {}
}
if (!node.fields) {
node.fields = {}
}
// Check that this field isn't owned by another plugin.
const fieldOwner = node.internal.fieldOwners[name]
if (fieldOwner && fieldOwner !== plugin.name) {
throw new Error(
stripIndent`
A plugin tried to update a node field that it doesn't own:
Node id: ${node.id}
Plugin: ${plugin.name}
name: ${name}
value: ${value}
`
)
}
// Update node
node.fields[name] = value
node.internal.fieldOwners[name] = plugin.name
return {
type: `ADD_FIELD_TO_NODE`,
plugin,
traceId,
payload: node,
}
}
/**
* Creates a link between a parent and child node. This is used when you
* transform content from a node creating a new child node. You need to add
* this new child node to the `children` array of the parent but since you
* don't have direct access to the immutable parent node, use this action
* instead.
* @param {Object} $0
* @param {Object} $0.parent the parent node object
* @param {Object} $0.child the child node object
* @example
* createParentChildLink({ parent: parentNode, child: childNode })
*/
actions.createParentChildLink = (
{ parent, child }: { parent: any, child: any },
plugin?: Plugin
) => {
// Update parent
parent.children.push(child.id)
parent.children = _.uniq(parent.children)
return {
type: `ADD_CHILD_NODE_TO_PARENT_NODE`,
plugin,
payload: parent,
}
}
/**
* Create a dependency between a page and data. Probably for
* internal use only.
* @param {Object} $0
* @param {string} $0.path the path to the page
* @param {string} $0.nodeId A node ID
* @param {string} $0.connection A connection type
* @private
*/
actions.createPageDependency = (
{
path,
nodeId,
connection,
}: { path: string, nodeId: string, connection: string },
plugin: string = ``
) => {
return {
type: `CREATE_COMPONENT_DEPENDENCY`,
plugin,
payload: {
path,
nodeId,
connection,
},
}
}
/**
* Delete dependencies between an array of pages and data. Probably for
* internal use only. Used when deleting pages.
* @param {Array} paths the paths to delete.
* @private
*/
actions.deleteComponentsDependencies = (paths: string[]) => {
return {
type: `DELETE_COMPONENTS_DEPENDENCIES`,
payload: {
paths,
},
}
}
/**
* When the query watcher extracts a graphq query, it calls
* this to store the query with its component.
* @private
*/
actions.replaceComponentQuery = ({
query,
componentPath,
}: {
query: string,
componentPath: string,
}) => {
return {
type: `REPLACE_COMPONENT_QUERY`,
payload: {
query,
componentPath,
},
}
}
/**
* Create a "job". This is a long-running process that are generally
* started as side-effects to GraphQL queries.
* [`gatsby-plugin-sharp`](/packages/gatsby-plugin-sharp/) uses this for
* example.
*
* Gatsby doesn't finish its bootstrap until all jobs are ended.
* @param {Object} job A job object with at least an id set
* @param {id} job.id The id of the job
* @example
* createJob({ id: `write file id: 123`, fileName: `something.jpeg` })
*/
actions.createJob = (job: Job, plugin?: ?Plugin = null) => {
return {
type: `CREATE_JOB`,
plugin,
payload: job,
}
}
/**
* Set (update) a "job". Sometimes on really long running jobs you want
* to update the job as it continues.
*
* @param {Object} job A job object with at least an id set
* @param {id} job.id The id of the job
* @example
* setJob({ id: `write file id: 123`, progress: 50 })
*/
actions.setJob = (job: Job, plugin?: ?Plugin = null) => {
return {
type: `SET_JOB`,
plugin,
payload: job,
}
}
/**
* End a "job".
*
* Gatsby doesn't finish its bootstrap until all jobs are ended.
* @param {Object} job A job object with at least an id set
* @param {id} job.id The id of the job
* @example
* endJob({ id: `write file id: 123` })
*/
actions.endJob = (job: Job, plugin?: ?Plugin = null) => {
return {
type: `END_JOB`,
plugin,
payload: job,
}
}
/**
* Set plugin status. A plugin can use this to save status keys e.g. the last
* it fetched something. These values are persisted between runs of Gatsby.
*
* @param {Object} status An object with arbitrary values set
* @example
* setPluginStatus({ lastFetched: Date.now() })
*/
actions.setPluginStatus = (
status: { [key: string]: mixed },
plugin: Plugin
) => {
return {
type: `SET_PLUGIN_STATUS`,
plugin,
payload: status,
}
}
/**
* Create a redirect from one page to another. Server redirects don't work out
* of the box. You must have a plugin setup to integrate the redirect data with
* your hosting technology e.g. the [Netlify
* plugin](/packages/gatsby-plugin-netlify/)).
*
* @param {Object} redirect Redirect data
* @param {string} redirect.fromPath Any valid URL. Must start with a forward slash
* @param {string} redirect.isPermanent This is a permanent redirect; defaults to temporary
* @param {string} redirect.toPath URL of a created page (see `createPage`)
* @param {string} redirect.redirectInBrowser Redirects are generally for redirecting legacy URLs to their new configuration. If you can't update your UI for some reason, set `redirectInBrowser` to true and Gatsby will handle redirecting in the client as well.
* @example
* createRedirect({ fromPath: '/old-url', toPath: '/new-url', isPermanent: true })
* createRedirect({ fromPath: '/url', toPath: '/zn-CH/url', Language: 'zn' })
*/
actions.createRedirect = ({
fromPath,
isPermanent = false,
redirectInBrowser = false,
toPath,
...rest
}) => {
let pathPrefix = ``
if (store.getState().program.prefixPaths) {
pathPrefix = store.getState().config.pathPrefix
}
return {
type: `CREATE_REDIRECT`,
payload: {
fromPath: `${pathPrefix}${fromPath}`,
isPermanent,
redirectInBrowser,
toPath: `${pathPrefix}${toPath}`,
...rest,
},
}
}
exports.actions = actions
exports.boundActionCreators = bindActionCreators(actions, store.dispatch)
| test "exports.default" when validating page component (#3941)
| packages/gatsby/src/redux/actions.js | test "exports.default" when validating page component (#3941) | <ide><path>ackages/gatsby/src/redux/actions.js
<ide> }
<ide> if (
<ide> !fileContent.includes(`export default`) &&
<del> !fileContent.includes(`module.exports`)
<add> !fileContent.includes(`module.exports`) &&
<add> !fileContent.includes(`exports.default`)
<ide> ) {
<ide> includesDefaultExport = false
<ide> } |
|
JavaScript | apache-2.0 | 9ce71d1099ef08b85024580c89d7b2b547ade42f | 0 | LLK/scratch-blocks,LLK/scratch-blocks,LLK/scratch-blocks,LLK/scratch-blocks,LLK/scratch-blocks | /**
* @license
* Visual Blocks Editor
*
* Copyright 2011 Google Inc.
* https://developers.google.com/blockly/
*
* 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.
*/
/**
* @fileoverview Flyout tray containing blocks which may be created.
* @author [email protected] (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Flyout');
goog.require('Blockly.Block');
goog.require('Blockly.Comment');
goog.require('Blockly.Events');
goog.require('Blockly.FlyoutButton');
goog.require('Blockly.Gesture');
goog.require('Blockly.Touch');
goog.require('Blockly.WorkspaceSvg');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.math.Rect');
goog.require('goog.userAgent');
/**
* Class for a flyout.
* @param {!Object} workspaceOptions Dictionary of options for the workspace.
* @constructor
*/
Blockly.Flyout = function(workspaceOptions) {
workspaceOptions.getMetrics = this.getMetrics_.bind(this);
workspaceOptions.setMetrics = this.setMetrics_.bind(this);
/**
* @type {!Blockly.Workspace}
* @private
*/
this.workspace_ = new Blockly.WorkspaceSvg(workspaceOptions);
this.workspace_.isFlyout = true;
/**
* Is RTL vs LTR.
* @type {boolean}
*/
this.RTL = !!workspaceOptions.RTL;
/**
* Flyout should be laid out horizontally vs vertically.
* @type {boolean}
* @private
*/
this.horizontalLayout_ = workspaceOptions.horizontalLayout;
/**
* Position of the toolbox and flyout relative to the workspace.
* @type {number}
* @private
*/
this.toolboxPosition_ = workspaceOptions.toolboxPosition;
/**
* Opaque data that can be passed to Blockly.unbindEvent_.
* @type {!Array.<!Array>}
* @private
*/
this.eventWrappers_ = [];
/**
* List of background buttons that lurk behind each block to catch clicks
* landing in the blocks' lakes and bays.
* @type {!Array.<!Element>}
* @private
*/
this.backgroundButtons_ = [];
/**
* List of visible buttons.
* @type {!Array.<!Blockly.FlyoutButton>}
* @private
*/
this.buttons_ = [];
/**
* List of event listeners.
* @type {!Array.<!Array>}
* @private
*/
this.listeners_ = [];
/**
* List of blocks that should always be disabled.
* @type {!Array.<!Blockly.Block>}
* @private
*/
this.permanentlyDisabled_ = [];
/**
* The toolbox that this flyout belongs to, or none if tihs is a simple
* workspace.
* @type {Blockly.Toolbox}
* @private
*/
this.parentToolbox_ = null;
/**
* The target position for the flyout scroll animation in pixels.
* Is a number while animating, null otherwise.
* @type {?number}
* @package
*/
this.scrollTarget = null;
};
/**
* Does the flyout automatically close when a block is created?
* @type {boolean}
*/
Blockly.Flyout.prototype.autoClose = false;
/**
* Whether the flyout is visible.
* @type {boolean}
* @private
*/
Blockly.Flyout.prototype.isVisible_ = false;
/**
* Whether the workspace containing this flyout is visible.
* @type {boolean}
* @private
*/
Blockly.Flyout.prototype.containerVisible_ = true;
/**
* Corner radius of the flyout background.
* @type {number}
* @const
*/
Blockly.Flyout.prototype.CORNER_RADIUS = 0;
/**
* Margin around the edges of the blocks in the flyout.
* @type {number}
* @const
*/
Blockly.Flyout.prototype.MARGIN = 12;
// TODO: Move GAP_X and GAP_Y to their appropriate files.
/**
* Gap between items in horizontal flyouts. Can be overridden with the "sep"
* element.
* @const {number}
*/
Blockly.Flyout.prototype.GAP_X = Blockly.Flyout.prototype.MARGIN * 3;
/**
* Gap between items in vertical flyouts. Can be overridden with the "sep"
* element.
* @const {number}
*/
Blockly.Flyout.prototype.GAP_Y = Blockly.Flyout.prototype.MARGIN;
/**
* Top/bottom padding between scrollbar and edge of flyout background.
* @type {number}
* @const
*/
Blockly.Flyout.prototype.SCROLLBAR_PADDING = 2;
/**
* Width of flyout.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.width_ = 0;
/**
* Height of flyout.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.height_ = 0;
/**
* Width of flyout contents.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.contentWidth_ = 0;
/**
* Height of flyout contents.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.contentHeight_ = 0;
/**
* Vertical offset of flyout.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.verticalOffset_ = 0;
/**
* Range of a drag angle from a flyout considered "dragging toward workspace".
* Drags that are within the bounds of this many degrees from the orthogonal
* line to the flyout edge are considered to be "drags toward the workspace".
* Example:
* Flyout Edge Workspace
* [block] / <-within this angle, drags "toward workspace" |
* [block] ---- orthogonal to flyout boundary ---- |
* [block] \ |
* The angle is given in degrees from the orthogonal.
*
* This is used to know when to create a new block and when to scroll the
* flyout. Setting it to 360 means that all drags create a new block.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.dragAngleRange_ = 70;
/**
* The fraction of the distance to the scroll target to move the flyout on
* each animation frame, when auto-scrolling. Values closer to 1.0 will make
* the scroll animation complete faster. Use 1.0 for no animation.
* @type {number}
*/
Blockly.Flyout.prototype.scrollAnimationFraction = 0.3;
/**
* Creates the flyout's DOM. Only needs to be called once. The flyout can
* either exist as its own svg element or be a g element nested inside a
* separate svg element.
* @param {string} tagName The type of tag to put the flyout in. This
* should be <svg> or <g>.
* @return {!Element} The flyout's SVG group.
*/
Blockly.Flyout.prototype.createDom = function(tagName) {
/*
<svg | g>
<path class="blocklyFlyoutBackground"/>
<g class="blocklyFlyout"></g>
</ svg | g>
*/
// Setting style to display:none to start. The toolbox and flyout
// hide/show code will set up proper visibility and size later.
this.svgGroup_ = Blockly.utils.createSvgElement(tagName,
{'class': 'blocklyFlyout', 'style' : 'display: none'}, null);
this.svgBackground_ = Blockly.utils.createSvgElement('path',
{'class': 'blocklyFlyoutBackground'}, this.svgGroup_);
this.svgGroup_.appendChild(this.workspace_.createDom());
return this.svgGroup_;
};
/**
* Initializes the flyout.
* @param {!Blockly.Workspace} targetWorkspace The workspace in which to create
* new blocks.
*/
Blockly.Flyout.prototype.init = function(targetWorkspace) {
this.targetWorkspace_ = targetWorkspace;
this.workspace_.targetWorkspace = targetWorkspace;
// Add scrollbar.
this.scrollbar_ = new Blockly.Scrollbar(this.workspace_,
this.horizontalLayout_, false, 'blocklyFlyoutScrollbar');
this.position();
Array.prototype.push.apply(this.eventWrappers_,
Blockly.bindEventWithChecks_(this.svgGroup_, 'wheel', this, this.wheel_));
// Dragging the flyout up and down (or left and right).
Array.prototype.push.apply(this.eventWrappers_,
Blockly.bindEventWithChecks_(this.svgGroup_, 'mousedown', this, this.onMouseDown_));
// A flyout connected to a workspace doesn't have its own current gesture.
this.workspace_.getGesture =
this.targetWorkspace_.getGesture.bind(this.targetWorkspace_);
// Get variables from the main workspace rather than the target workspace.
this.workspace_.getVariable =
this.targetWorkspace_.getVariable.bind(this.targetWorkspace_);
this.workspace_.getVariableById =
this.targetWorkspace_.getVariableById.bind(this.targetWorkspace_);
this.workspace_.getVariablesOfType =
this.targetWorkspace_.getVariablesOfType.bind(this.targetWorkspace_);
this.workspace_.deleteVariable =
this.targetWorkspace_.deleteVariable.bind(this.targetWorkspace_);
this.workspace_.deleteVariableById =
this.targetWorkspace_.deleteVariableById.bind(this.targetWorkspace_);
this.workspace_.renameVariable =
this.targetWorkspace_.renameVariable.bind(this.targetWorkspace_);
this.workspace_.renameVariableById =
this.targetWorkspace_.renameVariableById.bind(this.targetWorkspace_);
};
/**
* Dispose of this flyout.
* Unlink from all DOM elements to prevent memory leaks.
*/
Blockly.Flyout.prototype.dispose = function() {
this.hide();
Blockly.unbindEvent_(this.eventWrappers_);
if (this.scrollbar_) {
this.scrollbar_.dispose();
this.scrollbar_ = null;
}
if (this.workspace_) {
this.workspace_.targetWorkspace = null;
this.workspace_.dispose();
this.workspace_ = null;
}
if (this.svgGroup_) {
goog.dom.removeNode(this.svgGroup_);
this.svgGroup_ = null;
}
this.parentToolbox_ = null;
this.svgBackground_ = null;
this.targetWorkspace_ = null;
};
/**
* Set the parent toolbox of this flyout.
* @param {!Blockly.Toolbox} toolbox The toolbox that owns this flyout.
*/
Blockly.Flyout.prototype.setParentToolbox = function(toolbox) {
this.parentToolbox_ = toolbox;
};
/**
* Get the width of the flyout.
* @return {number} The width of the flyout.
*/
Blockly.Flyout.prototype.getWidth = function() {
return this.DEFAULT_WIDTH;
};
/**
* Get the height of the flyout.
* @return {number} The width of the flyout.
*/
Blockly.Flyout.prototype.getHeight = function() {
return this.height_;
};
/**
* Get the flyout's workspace.
* @return {!Blockly.WorkspaceSvg} The workspace inside the flyout.
* @package
*/
Blockly.Flyout.prototype.getWorkspace = function() {
return this.workspace_;
};
/**
* Is the flyout visible?
* @return {boolean} True if visible.
*/
Blockly.Flyout.prototype.isVisible = function() {
return this.isVisible_;
};
/**
* Set whether the flyout is visible. A value of true does not necessarily mean
* that the flyout is shown. It could be hidden because its container is hidden.
* @param {boolean} visible True if visible.
*/
Blockly.Flyout.prototype.setVisible = function(visible) {
var visibilityChanged = (visible != this.isVisible());
this.isVisible_ = visible;
if (visibilityChanged) {
this.updateDisplay_();
}
};
/**
* Set whether this flyout's container is visible.
* @param {boolean} visible Whether the container is visible.
*/
Blockly.Flyout.prototype.setContainerVisible = function(visible) {
var visibilityChanged = (visible != this.containerVisible_);
this.containerVisible_ = visible;
if (visibilityChanged) {
this.updateDisplay_();
}
};
/**
* Update the display property of the flyout based whether it thinks it should
* be visible and whether its containing workspace is visible.
* @private
*/
Blockly.Flyout.prototype.updateDisplay_ = function() {
var show = true;
if (!this.containerVisible_) {
show = false;
} else {
show = this.isVisible();
}
this.svgGroup_.style.display = show ? 'block' : 'none';
// Update the scrollbar's visiblity too since it should mimic the
// flyout's visibility.
this.scrollbar_.setContainerVisible(show);
};
/**
* Hide and empty the flyout.
*/
Blockly.Flyout.prototype.hide = function() {
if (!this.isVisible()) {
return;
}
this.setVisible(false);
// Delete all the event listeners.
for (var x = 0, listen; listen = this.listeners_[x]; x++) {
Blockly.unbindEvent_(listen);
}
this.listeners_.length = 0;
if (this.reflowWrapper_) {
this.workspace_.removeChangeListener(this.reflowWrapper_);
this.reflowWrapper_ = null;
}
// Do NOT delete the blocks here. Wait until Flyout.show.
// https://neil.fraser.name/news/2014/08/09/
};
/**
* Show and populate the flyout.
* @param {!Array|string} xmlList List of blocks to show.
* Variables and procedures have a custom set of blocks.
*/
Blockly.Flyout.prototype.show = function(xmlList) {
this.workspace_.setBulkUpdate(true);
this.hide();
this.clearOldBlocks_();
this.setVisible(true);
// Create the blocks to be shown in this flyout.
var contents = [];
var gaps = [];
this.permanentlyDisabled_.length = 0;
for (var i = 0, xml; xml = xmlList[i]; i++) {
// Handle dynamic categories, represented by a name instead of a list of XML.
// Look up the correct category generation function and call that to get a
// valid XML list.
if (typeof xml === 'string') {
var fnToApply = this.workspace_.targetWorkspace.getToolboxCategoryCallback(
xmlList[i]);
var newList = fnToApply(this.workspace_.targetWorkspace);
// Insert the new list of blocks in the middle of the list.
// We use splice to insert at index i, and remove a single element
// (the placeholder string). Because the spread operator (...) is not
// available, use apply and concat the array.
xmlList.splice.apply(xmlList, [i, 1].concat(newList));
xml = xmlList[i];
}
if (xml.tagName) {
var tagName = xml.tagName.toUpperCase();
var default_gap = this.horizontalLayout_ ? this.GAP_X : this.GAP_Y;
if (tagName == 'BLOCK') {
var curBlock = Blockly.Xml.domToBlock(xml, this.workspace_);
if (curBlock.disabled) {
// Record blocks that were initially disabled.
// Do not enable these blocks as a result of capacity filtering.
this.permanentlyDisabled_.push(curBlock);
}
contents.push({type: 'block', block: curBlock});
var gap = parseInt(xml.getAttribute('gap'), 10);
gaps.push(isNaN(gap) ? default_gap : gap);
} else if (xml.tagName.toUpperCase() == 'SEP') {
// Change the gap between two blocks.
// <sep gap="36"></sep>
// The default gap is 24, can be set larger or smaller.
// This overwrites the gap attribute on the previous block.
// Note that a deprecated method is to add a gap to a block.
// <block type="math_arithmetic" gap="8"></block>
var newGap = parseInt(xml.getAttribute('gap'), 10);
// Ignore gaps before the first block.
if (!isNaN(newGap) && gaps.length > 0) {
gaps[gaps.length - 1] = newGap;
} else {
gaps.push(default_gap);
}
} else if (tagName == 'BUTTON' || tagName == 'LABEL') {
// Labels behave the same as buttons, but are styled differently.
var isLabel = tagName == 'LABEL';
var curButton = new Blockly.FlyoutButton(this.workspace_,
this.targetWorkspace_, xml, isLabel);
contents.push({type: 'button', button: curButton});
gaps.push(default_gap);
}
}
}
this.layout_(contents, gaps);
// IE 11 is an incompetent browser that fails to fire mouseout events.
// When the mouse is over the background, deselect all blocks.
var deselectAll = function() {
var topBlocks = this.workspace_.getTopBlocks(false);
for (var i = 0, block; block = topBlocks[i]; i++) {
block.removeSelect();
}
};
this.listeners_.push(Blockly.bindEvent_(this.svgBackground_, 'mouseover',
this, deselectAll));
this.workspace_.setBulkUpdate(false);
this.reflow();
// Correctly position the flyout's scrollbar when it opens.
this.position();
this.reflowWrapper_ = this.reflow.bind(this);
this.workspace_.addChangeListener(this.reflowWrapper_);
this.recordCategoryScrollPositions_();
};
/**
* Store an array of category names and scrollbar positions.
* This is used when scrolling the flyout to cause a category to be selected.
* @private
*/
Blockly.Flyout.prototype.recordCategoryScrollPositions_ = function() {
this.categoryScrollPositions = [];
for (var i = 0; i < this.buttons_.length; i++) {
if (this.buttons_[i].getIsCategoryLabel()) {
var categoryLabel = this.buttons_[i];
this.categoryScrollPositions.push({
categoryName: categoryLabel.getText(),
position: this.horizontalLayout_ ?
categoryLabel.getPosition().x : categoryLabel.getPosition().y
});
}
}
};
/**
* Select a category using the scroll position.
* @param {number} pos The scroll position in pixels.
* @package
*/
Blockly.Flyout.prototype.selectCategoryByScrollPosition = function(pos) {
// If we are currently auto-scrolling, due to selecting a category by clicking on it,
// do not update the category selection.
if (this.scrollTarget) {
return;
}
var workspacePos = pos / this.workspace_.scale;
// Traverse the array of scroll positions in reverse, so we can select the furthest
// category that the scroll position is beyond.
for (var i = this.categoryScrollPositions.length - 1; i >= 0; i--) {
if (workspacePos > this.categoryScrollPositions[i].position) {
this.parentToolbox_.selectCategoryByName(this.categoryScrollPositions[i].categoryName);
return;
}
}
};
/**
* Step the scrolling animation by scrolling a fraction of the way to
* a scroll target, and request the next frame if necessary.
* @package
*/
Blockly.Flyout.prototype.stepScrollAnimation = function() {
if (!this.scrollTarget) {
return;
}
var scrollPos = this.horizontalLayout_ ?
-this.workspace_.scrollX : -this.workspace_.scrollY;
var diff = this.scrollTarget - scrollPos;
if (Math.abs(diff) < 1) {
this.scrollbar_.set(this.scrollTarget);
this.scrollTarget = null;
return;
}
this.scrollbar_.set(scrollPos + diff * this.scrollAnimationFraction);
// Polyfilled by goog.dom.animationFrame.polyfill
requestAnimationFrame(this.stepScrollAnimation.bind(this));
};
/**
* Delete blocks and background buttons from a previous showing of the flyout.
* @private
*/
Blockly.Flyout.prototype.clearOldBlocks_ = function() {
// Delete any blocks from a previous showing.
var oldBlocks = this.workspace_.getTopBlocks(false);
for (var i = 0, block; block = oldBlocks[i]; i++) {
if (block.workspace == this.workspace_) {
block.dispose(false, false);
}
}
// Delete any background buttons from a previous showing.
for (var j = 0; j < this.backgroundButtons_.length; j++) {
var rect = this.backgroundButtons_[j];
if (rect) goog.dom.removeNode(rect);
}
this.backgroundButtons_.length = 0;
for (var i = 0, button; button = this.buttons_[i]; i++) {
button.dispose();
}
this.buttons_.length = 0;
};
/**
* Add listeners to a block that has been added to the flyout.
* @param {!Element} root The root node of the SVG group the block is in.
* @param {!Blockly.Block} block The block to add listeners for.
* @param {!Element} rect The invisible rectangle under the block that acts as
* a button for that block.
* @private
*/
Blockly.Flyout.prototype.addBlockListeners_ = function(root, block, rect) {
this.listeners_.push(Blockly.bindEventWithChecks_(root, 'mousedown', null,
this.blockMouseDown_(block)));
this.listeners_.push(Blockly.bindEventWithChecks_(rect, 'mousedown', null,
this.blockMouseDown_(block)));
this.listeners_.push(Blockly.bindEvent_(root, 'mouseover', block,
block.addSelect));
this.listeners_.push(Blockly.bindEvent_(root, 'mouseout', block,
block.removeSelect));
this.listeners_.push(Blockly.bindEvent_(rect, 'mouseover', block,
block.addSelect));
this.listeners_.push(Blockly.bindEvent_(rect, 'mouseout', block,
block.removeSelect));
};
/**
* Handle a mouse-down on an SVG block in a non-closing flyout.
* @param {!Blockly.Block} block The flyout block to copy.
* @return {!Function} Function to call when block is clicked.
* @private
*/
Blockly.Flyout.prototype.blockMouseDown_ = function(block) {
var flyout = this;
return function(e) {
var gesture = flyout.targetWorkspace_.getGesture(e);
if (gesture) {
gesture.setStartBlock(block);
gesture.handleFlyoutStart(e, flyout);
}
};
};
/**
* Mouse down on the flyout background. Start a scroll drag.
* @param {!Event} e Mouse down event.
* @private
*/
Blockly.Flyout.prototype.onMouseDown_ = function(e) {
var gesture = this.targetWorkspace_.getGesture(e);
if (gesture) {
gesture.handleFlyoutStart(e, this);
}
};
/**
* Create a copy of this block on the workspace.
* @param {!Blockly.BlockSvg} originalBlock The block to copy from the flyout.
* @return {Blockly.BlockSvg} The newly created block, or null if something
* went wrong with deserialization.
* @package
*/
Blockly.Flyout.prototype.createBlock = function(originalBlock) {
var newBlock = null;
Blockly.Events.disable();
this.targetWorkspace_.setResizesEnabled(false);
try {
newBlock = this.placeNewBlock_(originalBlock);
//Force a render on IE and Edge to get around the issue described in
//Blockly.Field.getCachedWidth
if (goog.userAgent.IE || goog.userAgent.EDGE) {
var blocks = newBlock.getDescendants();
for (var i = blocks.length - 1; i >= 0; i--) {
blocks[i].render(false);
}
}
// Close the flyout.
Blockly.hideChaff();
} finally {
Blockly.Events.enable();
}
if (Blockly.Events.isEnabled()) {
Blockly.Events.setGroup(true);
Blockly.Events.fire(new Blockly.Events.Create(newBlock));
}
if (this.autoClose) {
this.hide();
}
return newBlock;
};
/**
* Reflow blocks and their buttons.
*/
Blockly.Flyout.prototype.reflow = function() {
if (this.reflowWrapper_) {
this.workspace_.removeChangeListener(this.reflowWrapper_);
}
var blocks = this.workspace_.getTopBlocks(false);
this.reflowInternal_(blocks);
if (this.reflowWrapper_) {
this.workspace_.addChangeListener(this.reflowWrapper_);
}
};
/**
* @return {boolean} True if this flyout may be scrolled with a scrollbar or by
* dragging.
* @package
*/
Blockly.Flyout.prototype.isScrollable = function() {
return this.scrollbar_ ? this.scrollbar_.isVisible() : false;
};
/**
* Copy a block from the flyout to the workspace and position it correctly.
* @param {!Blockly.Block} oldBlock The flyout block to copy.
* @return {!Blockly.Block} The new block in the main workspace.
* @private
*/
Blockly.Flyout.prototype.placeNewBlock_ = function(oldBlock) {
var targetWorkspace = this.targetWorkspace_;
var svgRootOld = oldBlock.getSvgRoot();
if (!svgRootOld) {
throw 'oldBlock is not rendered.';
}
// Create the new block by cloning the block in the flyout (via XML).
var xml = Blockly.Xml.blockToDom(oldBlock);
// The target workspace would normally resize during domToBlock, which will
// lead to weird jumps. Save it for terminateDrag.
targetWorkspace.setResizesEnabled(false);
// Using domToBlock instead of domToWorkspace means that the new block will be
// placed at position (0, 0) in main workspace units.
var block = Blockly.Xml.domToBlock(xml, targetWorkspace);
var svgRootNew = block.getSvgRoot();
if (!svgRootNew) {
throw 'block is not rendered.';
}
// The offset in pixels between the main workspace's origin and the upper left
// corner of the injection div.
var mainOffsetPixels = targetWorkspace.getOriginOffsetInPixels();
// The offset in pixels between the flyout workspace's origin and the upper
// left corner of the injection div.
var flyoutOffsetPixels = this.workspace_.getOriginOffsetInPixels();
// The position of the old block in flyout workspace coordinates.
var oldBlockPosWs = oldBlock.getRelativeToSurfaceXY();
// The position of the old block in pixels relative to the flyout
// workspace's origin.
var oldBlockPosPixels = oldBlockPosWs.scale(this.workspace_.scale);
// The position of the old block in pixels relative to the upper left corner
// of the injection div.
var oldBlockOffsetPixels = goog.math.Coordinate.sum(flyoutOffsetPixels,
oldBlockPosPixels);
// The position of the old block in pixels relative to the origin of the
// main workspace.
var finalOffsetPixels = goog.math.Coordinate.difference(oldBlockOffsetPixels,
mainOffsetPixels);
// The position of the old block in main workspace coordinates.
var finalOffsetMainWs = finalOffsetPixels.scale(1 / targetWorkspace.scale);
block.moveBy(finalOffsetMainWs.x, finalOffsetMainWs.y);
return block;
};
| core/flyout_base.js | /**
* @license
* Visual Blocks Editor
*
* Copyright 2011 Google Inc.
* https://developers.google.com/blockly/
*
* 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.
*/
/**
* @fileoverview Flyout tray containing blocks which may be created.
* @author [email protected] (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Flyout');
goog.require('Blockly.Block');
goog.require('Blockly.Comment');
goog.require('Blockly.Events');
goog.require('Blockly.FlyoutButton');
goog.require('Blockly.Gesture');
goog.require('Blockly.Touch');
goog.require('Blockly.WorkspaceSvg');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.math.Rect');
goog.require('goog.userAgent');
/**
* Class for a flyout.
* @param {!Object} workspaceOptions Dictionary of options for the workspace.
* @constructor
*/
Blockly.Flyout = function(workspaceOptions) {
workspaceOptions.getMetrics = this.getMetrics_.bind(this);
workspaceOptions.setMetrics = this.setMetrics_.bind(this);
/**
* @type {!Blockly.Workspace}
* @private
*/
this.workspace_ = new Blockly.WorkspaceSvg(workspaceOptions);
this.workspace_.isFlyout = true;
/**
* Is RTL vs LTR.
* @type {boolean}
*/
this.RTL = !!workspaceOptions.RTL;
/**
* Flyout should be laid out horizontally vs vertically.
* @type {boolean}
* @private
*/
this.horizontalLayout_ = workspaceOptions.horizontalLayout;
/**
* Position of the toolbox and flyout relative to the workspace.
* @type {number}
* @private
*/
this.toolboxPosition_ = workspaceOptions.toolboxPosition;
/**
* Opaque data that can be passed to Blockly.unbindEvent_.
* @type {!Array.<!Array>}
* @private
*/
this.eventWrappers_ = [];
/**
* List of background buttons that lurk behind each block to catch clicks
* landing in the blocks' lakes and bays.
* @type {!Array.<!Element>}
* @private
*/
this.backgroundButtons_ = [];
/**
* List of visible buttons.
* @type {!Array.<!Blockly.FlyoutButton>}
* @private
*/
this.buttons_ = [];
/**
* List of event listeners.
* @type {!Array.<!Array>}
* @private
*/
this.listeners_ = [];
/**
* List of blocks that should always be disabled.
* @type {!Array.<!Blockly.Block>}
* @private
*/
this.permanentlyDisabled_ = [];
/**
* The toolbox that this flyout belongs to, or none if tihs is a simple
* workspace.
* @type {Blockly.Toolbox}
* @private
*/
this.parentToolbox_ = null;
/**
* The target position for the flyout scroll animation in pixels.
* Is a number while animating, null otherwise.
* @type {?number}
* @package
*/
this.scrollTarget = null;
};
/**
* Does the flyout automatically close when a block is created?
* @type {boolean}
*/
Blockly.Flyout.prototype.autoClose = false;
/**
* Whether the flyout is visible.
* @type {boolean}
* @private
*/
Blockly.Flyout.prototype.isVisible_ = false;
/**
* Whether the workspace containing this flyout is visible.
* @type {boolean}
* @private
*/
Blockly.Flyout.prototype.containerVisible_ = true;
/**
* Corner radius of the flyout background.
* @type {number}
* @const
*/
Blockly.Flyout.prototype.CORNER_RADIUS = 0;
/**
* Margin around the edges of the blocks in the flyout.
* @type {number}
* @const
*/
Blockly.Flyout.prototype.MARGIN = 12;
// TODO: Move GAP_X and GAP_Y to their appropriate files.
/**
* Gap between items in horizontal flyouts. Can be overridden with the "sep"
* element.
* @const {number}
*/
Blockly.Flyout.prototype.GAP_X = Blockly.Flyout.prototype.MARGIN * 3;
/**
* Gap between items in vertical flyouts. Can be overridden with the "sep"
* element.
* @const {number}
*/
Blockly.Flyout.prototype.GAP_Y = Blockly.Flyout.prototype.MARGIN;
/**
* Top/bottom padding between scrollbar and edge of flyout background.
* @type {number}
* @const
*/
Blockly.Flyout.prototype.SCROLLBAR_PADDING = 2;
/**
* Width of flyout.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.width_ = 0;
/**
* Height of flyout.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.height_ = 0;
/**
* Width of flyout contents.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.contentWidth_ = 0;
/**
* Height of flyout contents.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.contentHeight_ = 0;
/**
* Vertical offset of flyout.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.verticalOffset_ = 0;
/**
* Range of a drag angle from a flyout considered "dragging toward workspace".
* Drags that are within the bounds of this many degrees from the orthogonal
* line to the flyout edge are considered to be "drags toward the workspace".
* Example:
* Flyout Edge Workspace
* [block] / <-within this angle, drags "toward workspace" |
* [block] ---- orthogonal to flyout boundary ---- |
* [block] \ |
* The angle is given in degrees from the orthogonal.
*
* This is used to know when to create a new block and when to scroll the
* flyout. Setting it to 360 means that all drags create a new block.
* @type {number}
* @private
*/
Blockly.Flyout.prototype.dragAngleRange_ = 70;
/**
* The fraction of the distance to the scroll target to move the flyout on
* each animation frame, when auto-scrolling. Values closer to 1.0 will make
* the scroll animation complete faster. Use 1.0 for no animation.
* @type {number}
*/
Blockly.Flyout.prototype.scrollAnimationFraction = 0.3;
/**
* Creates the flyout's DOM. Only needs to be called once. The flyout can
* either exist as its own svg element or be a g element nested inside a
* separate svg element.
* @param {string} tagName The type of tag to put the flyout in. This
* should be <svg> or <g>.
* @return {!Element} The flyout's SVG group.
*/
Blockly.Flyout.prototype.createDom = function(tagName) {
/*
<svg | g>
<path class="blocklyFlyoutBackground"/>
<g class="blocklyFlyout"></g>
</ svg | g>
*/
// Setting style to display:none to start. The toolbox and flyout
// hide/show code will set up proper visibility and size later.
this.svgGroup_ = Blockly.utils.createSvgElement(tagName,
{'class': 'blocklyFlyout', 'style' : 'display: none'}, null);
this.svgBackground_ = Blockly.utils.createSvgElement('path',
{'class': 'blocklyFlyoutBackground'}, this.svgGroup_);
this.svgGroup_.appendChild(this.workspace_.createDom());
return this.svgGroup_;
};
/**
* Initializes the flyout.
* @param {!Blockly.Workspace} targetWorkspace The workspace in which to create
* new blocks.
*/
Blockly.Flyout.prototype.init = function(targetWorkspace) {
this.targetWorkspace_ = targetWorkspace;
this.workspace_.targetWorkspace = targetWorkspace;
// Add scrollbar.
this.scrollbar_ = new Blockly.Scrollbar(this.workspace_,
this.horizontalLayout_, false, 'blocklyFlyoutScrollbar');
this.position();
Array.prototype.push.apply(this.eventWrappers_,
Blockly.bindEventWithChecks_(this.svgGroup_, 'wheel', this, this.wheel_));
// Dragging the flyout up and down (or left and right).
Array.prototype.push.apply(this.eventWrappers_,
Blockly.bindEventWithChecks_(this.svgGroup_, 'mousedown', this, this.onMouseDown_));
// A flyout connected to a workspace doesn't have its own current gesture.
this.workspace_.getGesture =
this.targetWorkspace_.getGesture.bind(this.targetWorkspace_);
// Get variables from the main workspace rather than the target workspace.
this.workspace_.getVariable =
this.targetWorkspace_.getVariable.bind(this.targetWorkspace_);
this.workspace_.getVariableById =
this.targetWorkspace_.getVariableById.bind(this.targetWorkspace_);
this.workspace_.getVariablesOfType =
this.targetWorkspace_.getVariablesOfType.bind(this.targetWorkspace_);
this.workspace_.deleteVariable =
this.targetWorkspace_.deleteVariable.bind(this.targetWorkspace_);
this.workspace_.deleteVariableById =
this.targetWorkspace_.deleteVariableById.bind(this.targetWorkspace_);
this.workspace_.renameVariable =
this.targetWorkspace_.renameVariable.bind(this.targetWorkspace_);
this.workspace_.renameVariableById =
this.targetWorkspace_.renameVariableById.bind(this.targetWorkspace_);
};
/**
* Dispose of this flyout.
* Unlink from all DOM elements to prevent memory leaks.
*/
Blockly.Flyout.prototype.dispose = function() {
this.hide();
Blockly.unbindEvent_(this.eventWrappers_);
if (this.scrollbar_) {
this.scrollbar_.dispose();
this.scrollbar_ = null;
}
if (this.workspace_) {
this.workspace_.targetWorkspace = null;
this.workspace_.dispose();
this.workspace_ = null;
}
if (this.svgGroup_) {
goog.dom.removeNode(this.svgGroup_);
this.svgGroup_ = null;
}
this.parentToolbox_ = null;
this.svgBackground_ = null;
this.targetWorkspace_ = null;
};
/**
* Set the parent toolbox of this flyout.
* @param {!Blockly.Toolbox} toolbox The toolbox that owns this flyout.
*/
Blockly.Flyout.prototype.setParentToolbox = function(toolbox) {
this.parentToolbox_ = toolbox;
};
/**
* Get the width of the flyout.
* @return {number} The width of the flyout.
*/
Blockly.Flyout.prototype.getWidth = function() {
return this.DEFAULT_WIDTH;
};
/**
* Get the height of the flyout.
* @return {number} The width of the flyout.
*/
Blockly.Flyout.prototype.getHeight = function() {
return this.height_;
};
/**
* Get the flyout's workspace.
* @return {!Blockly.WorkspaceSvg} The workspace inside the flyout.
* @package
*/
Blockly.Flyout.prototype.getWorkspace = function() {
return this.workspace_;
};
/**
* Is the flyout visible?
* @return {boolean} True if visible.
*/
Blockly.Flyout.prototype.isVisible = function() {
return this.isVisible_;
};
/**
* Set whether the flyout is visible. A value of true does not necessarily mean
* that the flyout is shown. It could be hidden because its container is hidden.
* @param {boolean} visible True if visible.
*/
Blockly.Flyout.prototype.setVisible = function(visible) {
var visibilityChanged = (visible != this.isVisible());
this.isVisible_ = visible;
if (visibilityChanged) {
this.updateDisplay_();
}
};
/**
* Set whether this flyout's container is visible.
* @param {boolean} visible Whether the container is visible.
*/
Blockly.Flyout.prototype.setContainerVisible = function(visible) {
var visibilityChanged = (visible != this.containerVisible_);
this.containerVisible_ = visible;
if (visibilityChanged) {
this.updateDisplay_();
}
};
/**
* Update the display property of the flyout based whether it thinks it should
* be visible and whether its containing workspace is visible.
* @private
*/
Blockly.Flyout.prototype.updateDisplay_ = function() {
var show = true;
if (!this.containerVisible_) {
show = false;
} else {
show = this.isVisible();
}
this.svgGroup_.style.display = show ? 'block' : 'none';
// Update the scrollbar's visiblity too since it should mimic the
// flyout's visibility.
this.scrollbar_.setContainerVisible(show);
};
/**
* Hide and empty the flyout.
*/
Blockly.Flyout.prototype.hide = function() {
if (!this.isVisible()) {
return;
}
this.setVisible(false);
// Delete all the event listeners.
for (var x = 0, listen; listen = this.listeners_[x]; x++) {
Blockly.unbindEvent_(listen);
}
this.listeners_.length = 0;
if (this.reflowWrapper_) {
this.workspace_.removeChangeListener(this.reflowWrapper_);
this.reflowWrapper_ = null;
}
// Do NOT delete the blocks here. Wait until Flyout.show.
// https://neil.fraser.name/news/2014/08/09/
};
/**
* Show and populate the flyout.
* @param {!Array|string} xmlList List of blocks to show.
* Variables and procedures have a custom set of blocks.
*/
Blockly.Flyout.prototype.show = function(xmlList) {
this.workspace_.setBulkUpdate(true);
this.hide();
this.clearOldBlocks_();
this.setVisible(true);
// Create the blocks to be shown in this flyout.
var contents = [];
var gaps = [];
this.permanentlyDisabled_.length = 0;
for (var i = 0, xml; xml = xmlList[i]; i++) {
// Handle dynamic categories, represented by a name instead of a list of XML.
// Look up the correct category generation function and call that to get a
// valid XML list.
if (typeof xml === 'string') {
var fnToApply = this.workspace_.targetWorkspace.getToolboxCategoryCallback(
xmlList[i]);
var newList = fnToApply(this.workspace_.targetWorkspace);
// Insert the new list of blocks in the middle of the list.
// We use splice to insert at index i, and remove a single element
// (the placeholder string). Because the spread operator (...) is not
// available, use apply and concat the array.
xmlList.splice.apply(xmlList, [i, 1].concat(newList));
xml = xmlList[i];
}
if (xml.tagName) {
var tagName = xml.tagName.toUpperCase();
var default_gap = this.horizontalLayout_ ? this.GAP_X : this.GAP_Y;
if (tagName == 'BLOCK') {
var curBlock = Blockly.Xml.domToBlock(xml, this.workspace_);
if (curBlock.disabled) {
// Record blocks that were initially disabled.
// Do not enable these blocks as a result of capacity filtering.
this.permanentlyDisabled_.push(curBlock);
}
contents.push({type: 'block', block: curBlock});
var gap = parseInt(xml.getAttribute('gap'), 10);
gaps.push(isNaN(gap) ? default_gap : gap);
} else if (xml.tagName.toUpperCase() == 'SEP') {
// Change the gap between two blocks.
// <sep gap="36"></sep>
// The default gap is 24, can be set larger or smaller.
// This overwrites the gap attribute on the previous block.
// Note that a deprecated method is to add a gap to a block.
// <block type="math_arithmetic" gap="8"></block>
var newGap = parseInt(xml.getAttribute('gap'), 10);
// Ignore gaps before the first block.
if (!isNaN(newGap) && gaps.length > 0) {
gaps[gaps.length - 1] = newGap;
} else {
gaps.push(default_gap);
}
} else if (tagName == 'BUTTON' || tagName == 'LABEL') {
// Labels behave the same as buttons, but are styled differently.
var isLabel = tagName == 'LABEL';
var curButton = new Blockly.FlyoutButton(this.workspace_,
this.targetWorkspace_, xml, isLabel);
contents.push({type: 'button', button: curButton});
gaps.push(default_gap);
}
}
}
this.layout_(contents, gaps);
// IE 11 is an incompetent browser that fails to fire mouseout events.
// When the mouse is over the background, deselect all blocks.
var deselectAll = function() {
var topBlocks = this.workspace_.getTopBlocks(false);
for (var i = 0, block; block = topBlocks[i]; i++) {
block.removeSelect();
}
};
this.listeners_.push(Blockly.bindEvent_(this.svgBackground_, 'mouseover',
this, deselectAll));
this.workspace_.setBulkUpdate(false);
this.reflow();
// Correctly position the flyout's scrollbar when it opens.
this.position();
this.reflowWrapper_ = this.reflow.bind(this);
this.workspace_.addChangeListener(this.reflowWrapper_);
this.recordCategoryScrollPositions_();
};
/**
* Store an array of category names and scrollbar positions.
* This is used when scrolling the flyout to cause a category to be selected.
* @private
*/
Blockly.Flyout.prototype.recordCategoryScrollPositions_ = function() {
this.categoryScrollPositions = [];
for (var i = 0; i < this.buttons_.length; i++) {
if (this.buttons_[i].getIsCategoryLabel()) {
var categoryLabel = this.buttons_[i];
this.categoryScrollPositions.push({
categoryName: categoryLabel.getText(),
position: this.horizontalLayout_ ?
categoryLabel.getPosition().x : categoryLabel.getPosition().y
});
}
}
};
/**
* Select a category using the scroll position.
* @param {number} pos The scroll position in pixels.
* @package
*/
Blockly.Flyout.prototype.selectCategoryByScrollPosition = function(pos) {
// If we are currently auto-scrolling, due to selecting a category by clicking on it,
// do not update the category selection.
if (this.scrollTarget) {
return;
}
var workspacePos = pos / this.workspace_.scale;
// Traverse the array of scroll positions in reverse, so we can select the furthest
// category that the scroll position is beyond.
for (var i = this.categoryScrollPositions.length - 1; i >= 0; i--) {
if (workspacePos > this.categoryScrollPositions[i].position) {
this.parentToolbox_.selectCategoryByName(this.categoryScrollPositions[i].categoryName);
return;
}
}
};
/**
* Step the scrolling animation by scrolling a fraction of the way to
* a scroll target, and request the next frame if necessary.
* @package
*/
Blockly.Flyout.prototype.stepScrollAnimation = function() {
if (!this.scrollTarget) {
return;
}
var scrollPos = this.horizontalLayout_ ?
-this.workspace_.scrollX : -this.workspace_.scrollY;
var diff = this.scrollTarget - scrollPos;
if (Math.abs(diff) < 1) {
this.scrollbar_.set(this.scrollTarget);
this.scrollTarget = null;
return;
}
this.scrollbar_.set(scrollPos + diff * this.scrollAnimationFraction);
// Polyfilled by goog.dom.animationFrame.polyfill
requestAnimationFrame(this.stepScrollAnimation.bind(this));
};
/**
* Delete blocks and background buttons from a previous showing of the flyout.
* @private
*/
Blockly.Flyout.prototype.clearOldBlocks_ = function() {
// Delete any blocks from a previous showing.
var oldBlocks = this.workspace_.getTopBlocks(false);
for (var i = 0, block; block = oldBlocks[i]; i++) {
if (block.workspace == this.workspace_) {
block.dispose(false, false);
}
}
// Delete any background buttons from a previous showing.
for (var j = 0, rect; rect = this.backgroundButtons_[j]; j++) {
goog.dom.removeNode(rect);
}
this.backgroundButtons_.length = 0;
for (var i = 0, button; button = this.buttons_[i]; i++) {
button.dispose();
}
this.buttons_.length = 0;
};
/**
* Add listeners to a block that has been added to the flyout.
* @param {!Element} root The root node of the SVG group the block is in.
* @param {!Blockly.Block} block The block to add listeners for.
* @param {!Element} rect The invisible rectangle under the block that acts as
* a button for that block.
* @private
*/
Blockly.Flyout.prototype.addBlockListeners_ = function(root, block, rect) {
this.listeners_.push(Blockly.bindEventWithChecks_(root, 'mousedown', null,
this.blockMouseDown_(block)));
this.listeners_.push(Blockly.bindEventWithChecks_(rect, 'mousedown', null,
this.blockMouseDown_(block)));
this.listeners_.push(Blockly.bindEvent_(root, 'mouseover', block,
block.addSelect));
this.listeners_.push(Blockly.bindEvent_(root, 'mouseout', block,
block.removeSelect));
this.listeners_.push(Blockly.bindEvent_(rect, 'mouseover', block,
block.addSelect));
this.listeners_.push(Blockly.bindEvent_(rect, 'mouseout', block,
block.removeSelect));
};
/**
* Handle a mouse-down on an SVG block in a non-closing flyout.
* @param {!Blockly.Block} block The flyout block to copy.
* @return {!Function} Function to call when block is clicked.
* @private
*/
Blockly.Flyout.prototype.blockMouseDown_ = function(block) {
var flyout = this;
return function(e) {
var gesture = flyout.targetWorkspace_.getGesture(e);
if (gesture) {
gesture.setStartBlock(block);
gesture.handleFlyoutStart(e, flyout);
}
};
};
/**
* Mouse down on the flyout background. Start a scroll drag.
* @param {!Event} e Mouse down event.
* @private
*/
Blockly.Flyout.prototype.onMouseDown_ = function(e) {
var gesture = this.targetWorkspace_.getGesture(e);
if (gesture) {
gesture.handleFlyoutStart(e, this);
}
};
/**
* Create a copy of this block on the workspace.
* @param {!Blockly.BlockSvg} originalBlock The block to copy from the flyout.
* @return {Blockly.BlockSvg} The newly created block, or null if something
* went wrong with deserialization.
* @package
*/
Blockly.Flyout.prototype.createBlock = function(originalBlock) {
var newBlock = null;
Blockly.Events.disable();
this.targetWorkspace_.setResizesEnabled(false);
try {
newBlock = this.placeNewBlock_(originalBlock);
//Force a render on IE and Edge to get around the issue described in
//Blockly.Field.getCachedWidth
if (goog.userAgent.IE || goog.userAgent.EDGE) {
var blocks = newBlock.getDescendants();
for (var i = blocks.length - 1; i >= 0; i--) {
blocks[i].render(false);
}
}
// Close the flyout.
Blockly.hideChaff();
} finally {
Blockly.Events.enable();
}
if (Blockly.Events.isEnabled()) {
Blockly.Events.setGroup(true);
Blockly.Events.fire(new Blockly.Events.Create(newBlock));
}
if (this.autoClose) {
this.hide();
}
return newBlock;
};
/**
* Reflow blocks and their buttons.
*/
Blockly.Flyout.prototype.reflow = function() {
if (this.reflowWrapper_) {
this.workspace_.removeChangeListener(this.reflowWrapper_);
}
var blocks = this.workspace_.getTopBlocks(false);
this.reflowInternal_(blocks);
if (this.reflowWrapper_) {
this.workspace_.addChangeListener(this.reflowWrapper_);
}
};
/**
* @return {boolean} True if this flyout may be scrolled with a scrollbar or by
* dragging.
* @package
*/
Blockly.Flyout.prototype.isScrollable = function() {
return this.scrollbar_ ? this.scrollbar_.isVisible() : false;
};
/**
* Copy a block from the flyout to the workspace and position it correctly.
* @param {!Blockly.Block} oldBlock The flyout block to copy.
* @return {!Blockly.Block} The new block in the main workspace.
* @private
*/
Blockly.Flyout.prototype.placeNewBlock_ = function(oldBlock) {
var targetWorkspace = this.targetWorkspace_;
var svgRootOld = oldBlock.getSvgRoot();
if (!svgRootOld) {
throw 'oldBlock is not rendered.';
}
// Create the new block by cloning the block in the flyout (via XML).
var xml = Blockly.Xml.blockToDom(oldBlock);
// The target workspace would normally resize during domToBlock, which will
// lead to weird jumps. Save it for terminateDrag.
targetWorkspace.setResizesEnabled(false);
// Using domToBlock instead of domToWorkspace means that the new block will be
// placed at position (0, 0) in main workspace units.
var block = Blockly.Xml.domToBlock(xml, targetWorkspace);
var svgRootNew = block.getSvgRoot();
if (!svgRootNew) {
throw 'block is not rendered.';
}
// The offset in pixels between the main workspace's origin and the upper left
// corner of the injection div.
var mainOffsetPixels = targetWorkspace.getOriginOffsetInPixels();
// The offset in pixels between the flyout workspace's origin and the upper
// left corner of the injection div.
var flyoutOffsetPixels = this.workspace_.getOriginOffsetInPixels();
// The position of the old block in flyout workspace coordinates.
var oldBlockPosWs = oldBlock.getRelativeToSurfaceXY();
// The position of the old block in pixels relative to the flyout
// workspace's origin.
var oldBlockPosPixels = oldBlockPosWs.scale(this.workspace_.scale);
// The position of the old block in pixels relative to the upper left corner
// of the injection div.
var oldBlockOffsetPixels = goog.math.Coordinate.sum(flyoutOffsetPixels,
oldBlockPosPixels);
// The position of the old block in pixels relative to the origin of the
// main workspace.
var finalOffsetPixels = goog.math.Coordinate.difference(oldBlockOffsetPixels,
mainOffsetPixels);
// The position of the old block in main workspace coordinates.
var finalOffsetMainWs = finalOffsetPixels.scale(1 / targetWorkspace.scale);
block.moveBy(finalOffsetMainWs.x, finalOffsetMainWs.y);
return block;
};
| Fix flyout labels causing flyout scrolling issues (#1301)
| core/flyout_base.js | Fix flyout labels causing flyout scrolling issues (#1301) | <ide><path>ore/flyout_base.js
<ide> }
<ide> }
<ide> // Delete any background buttons from a previous showing.
<del> for (var j = 0, rect; rect = this.backgroundButtons_[j]; j++) {
<del> goog.dom.removeNode(rect);
<add> for (var j = 0; j < this.backgroundButtons_.length; j++) {
<add> var rect = this.backgroundButtons_[j];
<add> if (rect) goog.dom.removeNode(rect);
<ide> }
<ide> this.backgroundButtons_.length = 0;
<ide> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.